方法MethodForThread()在不同的线程中工作,最后他必须在调用MethodForThread()方法的线程中回调方法AsyncCallbackMethod( ) 。我用类 Dispatcher 来做。但事实是Dispatcher.Invoke()没有调用此方法AsyncCallbackMethod()。我做错了什么,它不起作用?
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;
}
}
}