Looking for an example of a custom SynchronizationContext (Required for unit testing)

后端 未结 4 720
悲哀的现实
悲哀的现实 2020-12-03 01:50

I need a custom SynchronizationContext that:

  • Owns a single thread that runs \"Posts\" and \"Sends\" delegates
  • Does the send in the order they are sen
4条回答
  •  自闭症患者
    2020-12-03 02:18

    I have adapted the answer by Bond to remove the dependency on WPF (Dispatcher), and depend on WinForms instead:

    namespace ManagedHelpers.Threads
       {
       using System;
       using System.Collections.Generic;
       using System.Diagnostics;
       using System.Linq;
       using System.Text;
       using System.Threading;
       using System.Threading.Tasks;
       using System.Windows.Forms;
       using NUnit.Framework;
    
       public class STASynchronizationContext : SynchronizationContext, IDisposable
          {
          private readonly Control control;
          private readonly int mainThreadId;
    
          public STASynchronizationContext()
             {
             this.control = new Control();
    
             this.control.CreateControl();
    
             this.mainThreadId = Thread.CurrentThread.ManagedThreadId;
    
             if (Thread.CurrentThread.Name == null)
                {
                Thread.CurrentThread.Name = "AsynchronousTestRunner Main Thread";
                }
             }
    
          public override void Post(SendOrPostCallback d, object state)
             {
             control.BeginInvoke(d, new object[] { state });
             }
    
          public override void Send(SendOrPostCallback d, object state)
             {
             control.Invoke(d, new object[] { state });
             }
    
          public void Dispose()
             {
             Assert.AreEqual(this.mainThreadId, Thread.CurrentThread.ManagedThreadId);
    
             this.Dispose(true);
             GC.SuppressFinalize(this);
             }
    
          protected virtual void Dispose(bool disposing)
             {
             Assert.AreEqual(this.mainThreadId, Thread.CurrentThread.ManagedThreadId);
    
             if (disposing)
                {
                if (control != null)
                   {
                   control.Dispose();
                   }
                }
             }
    
          ~STASynchronizationContext()
             {
             this.Dispose(false);
             }
          }
       }
    

提交回复
热议问题