Welcome to MSDN Blogs Sign in | Join | Help

jaredpar's WebLog

Code, rants and ramblings of a programmer.

Syndication

News

Now Reading

Expert F#

What's a better book to read when learning F#?

Essential WPF

Thus far the best book I've read on WPF. Gets right down to working with WPF and the goals/history.

Purely Functional Data Structures

Reading this book makes me feel like I'm back in college. It will really get your mind going and is best read with a whiteboard handy.

Blog Roll

Eric Lippert
Dustin Campbell
Jon Skeet
Coding Horror
Brian McNamara
Hub FS
Full List

Simple class for tests involving a SynchronizationContext

Recently I had to test a class which heavily depended upon a SynchronizationContext.  This threw me off for about half an hour as I didn't want to write multi-threaded unit tests.  Multi-threaded code is difficult enough without adding needless threads. 

The solution I came up with is simple and gives the unit test a large degree of control over the execution of posted delegates.  The resulting tests were much easier to code and understand.

public sealed class TestSynchronizationContext : SynchronizationContext {
    private List<Tuple<SendOrPostCallback, object>> m_pending 
        = new List<Tuple<SendOrPostCallback, object>>();

    public override void Send(SendOrPostCallback d, object state) {
        d(state);
    }

    public override void Post(SendOrPostCallback d, object state) {
        m_pending.Add(Tuple.Create(d, state));
    }

    public void RunAllPosted() {
        m_pending.ForEach(x => x.First(x.Second));
    }
}

Published Monday, August 25, 2008 8:00 AM by Jared Parsons

Comments

# car insurance &raquo; Simple class for tests involving a SynchronizationContext @ Monday, August 25, 2008 8:08 AM

PingBack from http://hoursfunnywallpaper.cn/?p=2901

car insurance &raquo; Simple class for tests involving a SynchronizationContext

New Comments to this post are disabled
Page view tracker