BackgroundWorker in different AppDomain not synchronizing with main thread

One of my projects is creating an application framework and this consists of several libraries with "tools", base UI elements (forms, controls…) and a "hosting" application. In the near future I will probably dedicate one or more articles about this hosting application, it’s quite interesting. Basically the hosting application is responsible for "installing" (xcopy), updating and "running" applications in separate AppDomains.

The problem I encountered was that when a child application (running in its own AppDomain) used a BackgroundWorker this BackgroundWorker couldn’t synchronize with the main UI thread. This resulted in exceptions whenever the RunWorkerCompletedEventHandler wanted to update the UI. As a workaround I use this piece of code before creating the BackgroundWorker.

if (SynchronizationContext.Current == null)

{

    SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

}

In my framework this is encapsulated in a method on a base Form, this is the short version:

public void StartAsyncLongAction(

    DoWorkEventHandler action,

    ProgressChangedEventHandler progressChanged,

    RunWorkerCompletedEventHandler workerCompleted,

    string actionText,

    string finishedText)

{

    if (SynchronizationContext.Current == null)

    {

        SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

    }

    BackgroundWorker worker = new BackgroundWorker();           

    worker.DoWork += action;           

    if (workerCompleted != null) { worker.RunWorkerCompleted += workerCompleted; }           

    if (progressChanged != null)

    {

        worker.WorkerReportsProgress = true;

        worker.ProgressChanged += progressChanged;               

    }

    worker.RunWorkerAsync();

}

If somebody knows why this happens I would be very interested.

Advertisement
This entry was posted in .NET and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s