背景线上的火灾事件

道歉,我的问题和努力都不准确。 我正在开发具有不同组件的控制台应用程序。 现在我已将它们分离并希望它们使用异步发布者/订阅者方式进行交互; 类似于WPF。 所以在这种情况下,我将有一个主线程,它将始终存在,并根据请求它将调用事件,例如DataRequested将在后台线程上触发。 一旦后台线程完成进程,它将再次触发事件,例如DataCompleted,它应该返回到调用线程,即主线程。 我希望我的解释清楚。

So far I have coded below; where I have EventBroker. public class EventBroker { public static event EventHandler SubscriptionAdded; public static event EventHandler SubscriptionRemoved; private static volatile EventBroker instance; private static object syncRoot = new Object(); private static Dictionary<string, List> subscriptions; ///  /// Initializes a new instance of the  class. ///  private EventBroker() { } ///  /// Gets the instance. ///  /// The instance. public static EventBroker Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new EventBroker(); subscriptions = new Dictionary<string, List>(); } } } return instance; } } ///  /// Gets or sets the internal subscriptions dictionary. ///  /// The subscriptions. private static Dictionary<string, List> Subscriptions { get { return EventBroker.subscriptions; } set { lock (syncRoot) { EventBroker.subscriptions = value; } } } ///  /// Raises the subscription added event. ///  /// The  instance containing the event data. private static void OnSubscriptionAdded(EventArgs e) { if (SubscriptionAdded != null) SubscriptionAdded(instance, e); } ///  /// Raises the subscription removed event. ///  /// The  instance containing the event data. private static void OnSubscriptionRemoved(EventArgs e) { if (SubscriptionRemoved != null) SubscriptionRemoved(instance, e); } ///  /// Subscribe method to the specified event. ///  /// The id. /// The method Delegate to be invoked when Event fires. public static void Subscribe(string id, Delegate method) { //Check if there is a existing event List delegates = null; if (Subscriptions == null) Subscriptions = new Dictionary<string, List>(); if (Subscriptions.ContainsKey(id)) { delegates = subscriptions[id]; } else { delegates = new List(); Subscriptions.Add(id, delegates); } delegates.Add(method); OnSubscriptionAdded(new EventArgs()); } ///  /// Unsubscribe method from event notifications ///  /// The id. /// The method. public static void Unsubscribe(string id, Delegate method) { if (Subscriptions.ContainsKey(id)) { if (Subscriptions[id].Contains(method)) { Subscriptions[id].Remove(method); OnSubscriptionRemoved(new EventArgs()); } if (Subscriptions[id].Count == 0) Subscriptions.Remove(id); } } ///  /// Fire the specified event by and pass parameters. ///  /// The id. /// The args. public static void Execute(string id, object sender, EventArgs e) { if (Subscriptions.ContainsKey(id)) { for (int i = 0; i < Subscriptions[id].Count; i++) { Delegate x = Subscriptions[id][i]; DynamicInvoke(id, x, sender, e); if (!Subscriptions.ContainsKey(id)) break; } } } ///  /// Checks to see if target of invocation is still a valid /// (non-disposed objects). Then it dinamicly invokes Delegate. ///  /// Event ID /// Delegate to invoke /// Object array of arguments private static void DynamicInvoke(string id, Delegate x, object sender, EventArgs e) { if (x.Method != null) { if (x.Target is Control) { Control ctl = (Control)x.Target; if (ctl.IsDisposed) { Unsubscribe(id, x); return; } } if (x.Target == null) { Unsubscribe(id, x); return; } x.DynamicInvoke(sender, e); ***//this becomes blocking call untill EventHandle is completed and hangs Master Thread*** } } } 

我使用这个EventBroker来跟踪我的订阅者,一旦Publisher来了,我就会调用某个委托。 但它仅在Master线程上调用,并且被挂起。 我想在单独的线程上调用EventHandler。

  public class MasterClass { public MasterClass() { EventBroker.Subscribe("Topic2", new EventHandler<EventArgs>(CallBackfromWorker)); } public void InvokeTest() { EventArgs EventArgs = new EventArgs("Test"); EventBroker.Execute("Topic1", null, EventArgs); //I want both of this to be asynchronous. } public void CallBackfromWorker(object sender, EventArgs e) { Debug.Pring("Get Called Asynchronously from Worker thread through Event"); } } **//Worker Class** public class WorkerClass { public WorkerClass() { EventBroker.Subscribe("Topic1", new EventHandler<EventArgs>(HandleRapRequest1)); } public void HandleRapRequest1(string RAPRequest) //public void HandleRapRequest1(object sender, EventArgs e) { Logger.LogToDisplay("WorkerClass Request" + RAPRequest); Logger.LogToDisplay("AsyncClient : " + System.Threading.Thread.CurrentThread.IsBackground); Logger.LogToDisplay("AsyncClient : " + System.Threading.Thread.CurrentThread.ManagedThreadId); Logger.LogToDisplay("Going to Sleep"); System.Threading.Thread.Sleep(10000); ***//Hangs my Master Thread*** EventBroker.Execute("Topic2", null, EventArgs); //I want both of this to be asynchronous. } } 

所以底线是我在控制台应用程序中寻找基于异步事件的发布者/订阅者…类似于CAB事件罪SCSF和WPF …

谢谢

这很简单:

 public class Foo { public event Action MyEvent; public void FireEvent() { Action myevent = MyEvent; if (myevent != null) { Task.Factory.StartNew(() => myevent()) .ContinueWith(t => { //TODO code to run in UI thread after event runs goes here }, CancellationToken.None , TaskContinuationOptions.None , TaskScheduler.FromCurrentSynchronizationContext()); } } } 

如果您使用的是C#5.0,则可以使用await来简化此代码:

 public class Foo { public event Action MyEvent; public async Task FireEvent() { Action myevent = MyEvent; if (MyEvent != null) { await Task.Run(() => myevent()); //TODO code to run in UI thread after event runs goes here } } } 

如果您不需要在UI线程中运行的代码在事件处理程序全部完成后启动,并且它可以继续同时继续在UI线程上运行,您还可以将代码简化为:

 public class Foo { public event Action MyEvent; public void FireEvent() { Action myevent = MyEvent; if (MyEvent != null) { Task.Factory.StartNew(() => myevent()); //TODO code to run in UI thread while event handlers run goes here } } }