方法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;
}
}
}
您正在使用WPF調度員,但我看不到任何東西產生任何WPF控件等,你肯定有,甚至* *是一個調度員? –
我認爲CurrentDispatcher會創建一個新的,如果沒有一個,但一個Dispatcher甚至可以在Thread.Sleep期間做任何事情? – Dirk
Jon Skeet,也就是在控制檯應用程序Dispatcher中不起作用? –