2013-06-13 55 views
0

方法MethodForThread()的作品在不同的線程,並在年底他有回調方法AsyncCallbackMethod()在線程中調用這個方法MethodForThread( )。我使用Class Dispatcher來完成它。但事實是,Dispatcher.Invoke()不會調用此方法AsyncCallbackMethod()。我做錯了什麼,它不起作用?Dispatcher.Invoke()調用沒有指定的委託

using System; 
using System.Threading; 
using System.Windows.Threading; 

namespace EventsThroughDispatcher 
{ 
    class Program2 
    { 
     public delegate void AsyncCallback(); 

     static void Main(string[] args) 
     { 
      Thread.CurrentThread.Name = "MainThread"; 

      Thread thrdSending = new Thread(MethodForThread); 
      thrdSending.Name = "WorkingThread"; 
      ThreadParameters tp = new ThreadParameters(); 
      tp.DispatcherForParentThread = Dispatcher.CurrentDispatcher; 
      tp.SendingCompleteCallback = AsyncCallbackMethod; 
      Console.WriteLine("Start"); 
      thrdSending.Start(tp); 

      while (!Console.KeyAvailable) System.Threading.Thread.Sleep(100); 
     } 

     static private void AsyncCallbackMethod() 
     { 
      Console.WriteLine("Callback invoked from thread: " + Thread.CurrentThread.Name + " " + Thread.CurrentThread.ManagedThreadId); 
     } 

     static void MethodForThread(object threadParametersObj) 
     { 
      ThreadParameters tp = (ThreadParameters)threadParametersObj; 
      Thread.Sleep(1000); 
      tp.DispatcherForParentThread.Invoke(tp.SendingCompleteCallback, null); //this not working 
      //tp.DispatcherForParentThread.BeginInvoke(tp.SendingCompleteCallback, null); //and this not working too 
      Console.WriteLine("WorkingThread exited"); 
     } 

     private class ThreadParameters 
     { 
      public Dispatcher DispatcherForParentThread; 
      public AsyncCallback SendingCompleteCallback; 
     } 
    } 
} 
+0

您正在使用WPF調度員,但我看不到任何東西產生任何WPF控件等,你肯定有,甚至* *是一個調度員? –

+0

我認爲CurrentDispatcher會創建一個新的,如果沒有一個,但一個Dispatcher甚至可以在Thread.Sleep期間做任何事情? – Dirk

+0

Jon Skeet,也就是在控制檯應用程序Dispatcher中不起作用? –

回答

2

您的解決方案無法在此表單中使用。 Dispatcher對象可用於在UI中進行更改(可將操作傳遞給調度程序,並傳遞給消息驅動的WIN32 API,以在UI上執行更改)。

如果你調試你的代碼,你可以看到Dispatcher.HasStarted標誌是false,所以它不會傳遞任何東西給UIThread。

我建議您使用異步設計模式。

您可以在這裏找到實現:

http://www.codeproject.com/Articles/14898/Asynchronous-design-patterns

2

你有一個最終的問題:

while (!Console.KeyAvailable) System.Threading.Thread.Sleep(100); 

這將阻止任何調度運行。但是你似乎在一個控制檯應用程序中使用它,我不確定這是否會起作用。調度員需要一個「消息泵」。

+0

感謝您的回答。好的,我會尋找另一種解決問題的方法... –