寻找自定义 SynchronizationContext 的示例(单元测试需要) [英] Looking for an example of a custom SynchronizationContext (Required for unit testing)

查看:23
本文介绍了寻找自定义 SynchronizationContext 的示例(单元测试需要)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个自定义的SynchronizationContext:

  • 拥有一个线程,运行Posts"和Sends"委托
  • 是否按发送顺序发送
  • 不需要其他方法

我需要这个,所以我可以对一些线程代码进行单元测试,这些代码将在实际应用程序中与 WinForm 通信.

I need this so I can unit test some threading code that will talk to WinForm in the real application.

在我自己写之前,我希望有人可以给我指出一个简单(而且很小)的实现.

Before I write my own, I was hoping that someone could point me to a simple (and small) implementations.

推荐答案

这个是我前段时间写的,没有版权问题,也没有保证(系统没有投产):

This one was written by me some time ago, no issues with copyright, no guarantees either(the system didn't go into production):

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();
        }
    }
}

这篇关于寻找自定义 SynchronizationContext 的示例(单元测试需要)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆