tags:

views:

36

answers:

1

I'm attempting to NUnit test adding an element to a collection from a new thread. This is the test function I'm using:

[Test]
public void WorkerThreadAccess()
{
    string foo = "Foo";
    Collection<string> collection = new Collection<string>();
    System.Threading.Thread thread = 
              new System.Threading.Thread(() => collection.Add(foo));
    thread.Start();

    Collection<string> expected = new Collection<string> { foo };
    System.Threading.Thread.Sleep(0);
    CollectionAssert.AreEqual(expected, collection);
}

When I run the test once, it passes. However on every subsequent test without closing NUnit GUI, NUnit fails the Assert with a weird error:

Expected and actual are both <System.Collections.ObjectModel.Collection1[System.String]`> with 1 elements
Values differ at index [0]
String lengths are both 3. Strings differ at index -1.
Expected: "Foo"
But was: "Foo"

Can anyone give some insight to what is going wrong? The elements look the same to me, and index -1 should only be returned on an IndexOf() error.

EDIT: I'm using NUnit 2.5.7

A: 

try replacing System.Threading.Thread.Sleep(0); with thread.Join();

What you actually want is to wait for the second thread to complete, not just pause the current one.

liho1eye
That was exactly it (and I learned a new method). Do you think you can explain why yielding my thread caused an error if the function was called twice in a process?
bsg
`Sleep(0)` simply returns control to the OS (or is it processor?), which picks another thread from it's list of active threads. That in no way implies that your second thread will be picked nor that your second thread is complete by the time control is returned to your main thread.Why does running it second time cause the error, but not the first? No idea... Some kind of resource allocation/compilation/voodoo magic overheads affecting first execution maybe?But its clear that your `collection` is still being modified when `CollectionAssert.AreEqual(expected, collection);` is executed.
liho1eye