Cross Thread Communication in Windows Forms: Part III


Here is Part 2

In this last article in the series we will use another approach to perform cross thread communication in Windows Forms; well this is something I personally prefer and use very often when working with Windows Forms.

We will be using the SynchronizationContext Class which is available in the framework. Well for those of you who do not know much about this, I suggest that you to visit this article. This is one of the most comprehensive contents about SynchronizationContext class, much more than the MSDN or any other source on the internet.

So, again this time we will use the same approach as we did in the previous articles: declare a variable of the SynchronizationContext type and set it in the constructor:

private SynchronizationContext  m_sync = null;

And in the constructor:

m_sync = SynchronizationContext.Current;

Let us define a method to simulate a long running task and that will be called on a separate thread:

private void SyncMethod(object args)
{
    Thread.Sleep(5000);
    m_sync.Post(new SendOrPostCallback(SyncMarshalled), args);
}

Next let us define a button click handler for the SyncMarshal button:

private void btnSync_Click(object sender, EventArgs e)
{
    EnableButtons(false);
    progressBar1.Visible = true;
    m_workThread = new Thread(new ParameterizedThreadStart(SyncMethod));
    m_workThread.Start("Synchronization");
}

Again as you see here on the button click we create a new Thread and invoke the SyncMethod that simmulates our long running task. When the thread Sleep method is over we make use of the Post() method of SynchronizationContext which internally takes care of marshalling back our method back to the UI thread. For more details of how the Post() method works, you can go to the link which I earlier mentioned in the article.

private void SyncMarshalled(object args)
{
    EnableButtons(true);
    progressBar1.Visible = false;
    richTextBox1.AppendText("Marshalled using " + Convert.ToString(args));
}

This is the method that gets called when a call is marshalled back to the UI thread again. Again to verify that you can do the same as we did in the previous two parts of the article. (I am leaving this for the readers to verify the same for them).

This concludes my series on cross thread communication in Window Forms. Hope it help fellow coders and makes their learning fruitful and enjoyable; until then enjoy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all