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

时间:2013-06-13 11:48:22

标签: c# multithreading dispatcher

方法 MethodForThread()在不同的线程中工作,最后他必须在被称为方法 AsyncCallbackMethod() > MethodForThread()即可。我是用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;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

你有一个明确的问题:

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

这将阻止任何调度程序运行。但是你似乎在控制台应用程序中使用它,我不确定它是否会起作用。调度员需要“消息泵”。

答案 1 :(得分:2)

您的解决方案无法以此形式运行。 Dispatcher对象可用于在UI上进行更改(您可以将操作传递给调度程序,并将其传递给消息驱动的WIN32 API,以在UI上执行更改)。

如果您调试代码,您会看到Dispatcher.HasStarted标志为false,因此它不会将任何内容传递给UIThread。

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

您可以在此处找到实施方案:

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