Testing BackgroundWorker-based code

186 views
Skip to first unread message

Steve Robbins

unread,
Mar 4, 2010, 5:52:54 PM3/4/10
to NUnit-Discuss
I have code that uses a BackgroundWorker to handle a long
computation. Since BackgroundWorker uses magic to ensure that the
RunWorkerCompleted event is raised on the main thread, the event
handler can safely manipulate shared state.

I have discovered, however, that BackgroundWorker behaves differently
when run without a GUI event loop. For example, it runs differently
in NUnit. Specifically, the RunWorkerCompleted event is raised on a
thread different from the main thread (used to run the unit test
cases). This creates a race condition that we occasionally lose.

What is the recommended fix for this?

Thanks,
-Steve

Charlie Poole

unread,
Mar 4, 2010, 7:54:47 PM3/4/10
to nunit-...@googlegroups.com
Hi Steve,

I'm afraid the answer is that you are expecting behavior, which
is not guaranteed by the BackgroundWorker, but which occurs
as a side effect of the object implementing the handler being
a Control. This is only a guess, but I know I've written code
like that myself, to avoid calling a Control on the wrong thread.

Charlie

> --
> You received this message because you are subscribed to the
> Google Groups "NUnit-Discuss" group.
> To post to this group, send email to nunit-...@googlegroups.com.
> To unsubscribe from this group, send email to
> nunit-discus...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/nunit-discuss?hl=en.
>
>

Gerard Meszaros

unread,
Mar 4, 2010, 10:35:49 PM3/4/10
to nunit-...@googlegroups.com
Try using a Humble Executible. This leaves a Plain Ordinary Testable Object that implements the real behavior you want to verify.

See http://xunitpatterns.com/Humble%20Object.html#Humble%20Executable

Gerard
-- 
Gerard Meszaros
1-403-827-2967

Steve Robbins

unread,
Mar 10, 2010, 8:00:28 AM3/10/10
to NUnit-Discuss
Hi,

Thanks to Gerard Meszaros for suggesting a Humble Executable; that's
what I've done.


On Mar 4, 6:54 pm, "Charlie Poole" <char...@nunit.com> wrote:
> Hi Steve,
>
> I'm afraid the answer is that you are expecting behavior, which
> is not guaranteed by the BackgroundWorker, but which occurs
> as a side effect of the object implementing the handler being
> a Control. This is only a guess, but I know I've written code
> like that myself, to avoid calling a Control on the wrong thread.

You are likely right. I cannot find any documentation that explicitly
states that the events are processed on the UI thread. The closest
I can find is a note in the class documentation [1] that says

You must be careful not to manipulate any user-interface objects
in your DoWork event handler. Instead, communicate to the user
interface through the ProgressChanged and RunWorkerCompleted
events.

Regards,
-Steve

[1] http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Reply all
Reply to author
Forward
0 new messages