Async delegates, illegal cross thread UI control access

Ron <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <4C4E8926CBE14656BA51289124528A51@pandora>
Hi all,

I've encountered a situation where I thought VS2005 would warn me about a
illegal cross thread UI call. I actually wanted the error to happen because
I'm doing a demo for my peers on the Asynchronous Programming Model.

WinForms app, long running web service call of 3-5 seconds. Don't want to
synchronously invoke the service call, and not using the asynchronous
methods in the proxy yet.

The app is demonstrating the Asynchronous Programming Model ala MSDN docs to
my peers.

Step 1. Create a delegate to match the service call.

delegate Image GetMapImageDelegate();

Step 2. Create a delegate instance, invoke it

void btnGetMap_Click()
{
 GetMapImageDelegate del = new GetMapImageDelegate(GetMapImage);
 del.BeginInvoke(OnGetMapImageComplete, del);
}

Image GetMapImage()
{
 // long running service call here
 // return image;
}

Step 3. In the callback, end the async invocation, getting the results

void OnGetMapImageComplete(IAsyncResult ar)
{
 GetMapImageDelegate del = ar.AsycnState as GetMapImageDelegate;
 Image image = del.EndInvoke(ar);

 // i expect this to cause the cross-thread error
 pictureBox.Image = image;
}

My understanding is that the thread in OnGetMapImageComplete is a thread
pool thread, and therefore accessing the pictureBox control should be
illegal. I traced the Thread.CurrentThread.ManagedThreadID in each method,
and showed that there are two different threads: btnGetMap_Click had ID 10,
all others were 11.

I was all prepared to create yet another delegate to handle displaying the
image with the check for InvokeRequired pattern, but if the error (cross
thread access to UI control) doesn't exist, then...well it isnt' necessary
to do that.

Any explanation as to why this is not occuring is appreciated.

Ron
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.