Thursday, February 5, 2009

About SynchronizationContext

A SynchronizationContext allows a thread to communicate with another thread. In .Net framework, WinForms thread context and WPF thread context provide a customer synchronization. A Windows Forms threading model prefers that any user interface code runs directly on the main "user interface" thread. (Contrast to ASP.NET, whre most work is done inside a thread pool so that asynchronous calls can happen on any thread in that pool).

ex.

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button_Click(object sender, EventArgs e)
{
//get an instance of SynchronizationContext class by calling
//the static Current property of SynchronizationContext class
SynchronizationContext uiContext = SynchronizationContext.Current;
Thread thread = new Thread(Run);
thread.Start(uiContext);
}
private void Run(object state)
{
SynchronizationContext uiContext = state as SynchronizationContext;
//Post or Send method to call some code, Post of Send method takes
//two parameters, a delegate pointing to a method and a state object
uiContext.Post(UpdateUI, "Hi");
}
private void UpdateUI(object state)
{
//state object is a string
string text = state as string;
mListBox.Items.Add(text);
}
}

Send and Post are two possible methods you can marshal code to UI thread. The difference is Send is "Synchronous", calling send will execute the code but block until the executing code complete until returning. Post is "Asynchronous", calling Post is more like fire-and-forget in that it queues up the request and returns immediatedly if possible.

No comments: