C# The calling thread cannot access this object because a different thread owns it.

One of the common problems encountered during multi-threading is when you try to set a Windows Control value from a different thread. I also faced this issue while implementing the following code:

private async void TestAsyncMethodVoid()
{
    System.Net.Http.HttpClient hClient = new System.Net.Http.HttpClient();
    string content = String.Empty;
    try
    {
        content = await hClient.GetStringAsync("http://www.microsoft.com").ConfigureAwait(false);
    }
    catch (Exception ex)
    {
        content = ex.Message;
    }
    btn00.Content = content;
}

btn00 is a button control whose value I was trying to set here using async/await as the value was coming over a network call. You may have some other case scenarios also where you’d want to set a control’s property directly from the thread. So to do that we’re gonna use, Dispatcher.Invoke method.

It executes the specified delegate synchronously on the thread the Dispatcher is associated with. Look at the following code with correction:

private async void TestAsyncMethodVoid()
{
	System.Net.Http.HttpClient hClient = new System.Net.Http.HttpClient();
	string content = String.Empty;
	try    
	{
		content = await hClient.GetStringAsync("http://www.microsoft.com").ConfigureAwait(false);
	}
	catch (Exception ex)
	{
		content = ex.Message;
	}
	this.Dispatcher.Invoke(() =>
	{
		btn00.Content = content;
	});
}

This code now works without any glitches.

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s