tags:

views:

20

answers:

0

It's been asked and answered but I'm not getting it.

In my NUnit tests, I create a Canvas. I save off the dispatcher. Then I create a thread to "LoadData". From LoadData i need to Dispatcher.Invoke back to the thread. I don't have a strategy for pausing or keeping the primary test thread running, and if I do pause or suspend the primary test thread. the Dispatcher.Invoke hangs because primary thread is suspended. I seen the stuff on DispatcherFrame but that is oriented around BeginInvoke. If you see the sample, I'm just newing something up, so to deal with beginInvoke and dispatcher frame seems painful. Particularly, since it works in the app, just not in the unit test.

I am aware of the Nunit STA issues. I run TestDriven.Net which is in STA mode by default.

Any comments, ideas appreciated.

   [TestFixture]
public class ThreadedTests
{
    List<ContentControl> _list = new List<ContentControl>();
    Dispatcher _dispatcher;

    [Test]
    public void Test()
    {
        _list.Clear();

        Debug.WriteLine(String.Format("Test on: {0}", Thread.CurrentThread.ManagedThreadId));
        Canvas canvas = new Canvas();
        _dispatcher = canvas.Dispatcher;

        Thread dataThread = new Thread(   loadData );
        dataThread.IsBackground = true;
        dataThread.Priority = ThreadPriority.Lowest;
        dataThread.Start();

        while (_list.Count == 0)
        {
            // tried something like this    
            Thread.CurrentThread.Suspend();
            Thread.CurrentThread.Resume();
        }

        Assert.IsTrue(_list.Count > 0);
    }
    void loadData()
    {
        Debug.WriteLine(String.Format("LoadData on: {0}", Thread.CurrentThread.ManagedThreadId));

        for (int i = 0; i < 5; i++)
        {
            // want to new back on Gui thread (where the canvas was created)
            //ContentControl control = new ContentControl();

            //2) Blocks here as it tries to get back to original thread, but it is currently suspended
            ContentControl control = (ContentControl)_dispatcher.Invoke(new Func<ContentControl>(createNewItem),null);

            _list.Add(control);
        }

        return ;
    }

    ContentControl createNewItem()
    {
        Debug.WriteLine(String.Format("Create Control on: {0}", Thread.CurrentThread.ManagedThreadId));
        return new ContentControl()  ;
    }
}