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