c# – 寻找一个自定义SynchronizationContext的示例(单元测试所需)

我需要一个自定义的SynchronizationContext

拥有运行“帖子”和“发送”代理的单个线程
>按发送的顺序发送
>不需要其他方法

我需要这样做,所以我可以单元测试一些线程代码,将在实际应用程序中与WinForm通信。

在我自己编写之前,我希望有人能指出一个简单的(和小的)实现。

这是一段时间以前由我写的,没有版权问题,也不保证(系统没有投入生产):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Threading;

namespace ManagedHelpers.Threads
{
    public class STASynchronizationContext : SynchronizationContext, IDisposable
    {
        private readonly Dispatcher dispatcher;
        private object dispObj;
        private readonly Thread mainThread;

        public STASynchronizationContext()
        {
            mainThread = new Thread(MainThread) { Name = "STASynchronizationContextMainThread", IsBackground = false };
            mainThread.SetApartmentState(ApartmentState.STA);
            mainThread.Start();

            //wait to get the main thread's dispatcher
            while (Thread.VolatileRead(ref dispObj) == null)
                Thread.Yield();

            dispatcher = dispObj as Dispatcher;
        }

        public override void Post(SendOrPostCallback d, object state)
        {
            dispatcher.BeginInvoke(d, new object[] { state });
        }

        public override void Send(SendOrPostCallback d, object state)
        {
            dispatcher.Invoke(d, new object[] { state });
        }

        private void MainThread(object param)
        {
            Thread.VolatileWrite(ref dispObj, Dispatcher.CurrentDispatcher);
            Console.WriteLine("Main Thread is setup ! Id = {0}", Thread.CurrentThread.ManagedThreadId);
            Dispatcher.Run();
        }

        public void Dispose()
        {
            if (!dispatcher.HasShutdownStarted && !dispatcher.HasShutdownFinished)
                dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);

            GC.SuppressFinalize(this);
        }

        ~STASynchronizationContext()
        {
            Dispose();
        }
    }
}
http://stackoverflow.com/questions/1882417/looking-for-an-example-of-a-custom-synchronizationcontext-required-for-unit-tes

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 寻找一个自定义SynchronizationContext的示例(单元测试所需)