Dispatcher.Invoke()没有调用指定的委托

本文关键字:调用 Invoke Dispatcher | 更新日期: 2023-09-27 18:18:17

方法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;
        }
    }
}

Dispatcher.Invoke()没有调用指定的委托

您的解决方案在这种形式下不起作用。Dispatcher对象可以简单地用于在UI上进行更改(您可以将一个操作传递给Dispatcher,然后它传递给消息驱动的WIN32 API,以在UI上执行更改)。

如果你调试你的代码,你可以看到Dispatcher。HasStarted标志为false,因此它不会向UIThread传递任何内容。

我建议您使用异步设计模式。

你可以在这里找到实现:

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

你有一个明确的问题:

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

这将阻止任何调度程序运行。但你似乎在控制台应用中使用了这个,我不确定这是否会奏效。调度程序需要一个"消息泵"。