0

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

2 回答 2

2

你有一个明确的问题:

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

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

于 2013-06-13T11:59:18.117 回答
2

您的解决方案不适用于这种形式。简而言之,Dispatcher 对象可用于对 UI 进行更改(您可以将操作传递给调度程序,并将其传递给消息驱动的 WIN32 API,以执行对 UI 的更改)。

如果你调试你的代码,你可以看到 Dispatcher.HasStarted 标志是假的,所以它不会向 UIThread 传递任何东西。

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

你可以在这里找到实现:

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

于 2013-06-13T12:15:01.347 回答