[.net] C# threading, callbacks and main thread.

Started by
1 comment, last by BradSnobar 17 years, 2 months ago
How does the callback function with delegate threads work (AsyncCallback)? Is it executed in the delegate thread or in the main thread? Is it possible to assign a callback for a managed thread (one created using the Thread class)? Is there some method for executing a function in the main thread, when called from a 'worker' thread? Thanks!
Advertisement
Asynchronous callbacks (sockets etc and when you've asked for one) will typically run in their own thread. You'll probably want to look at the Invoke or Begin/EndInvoke stuff on the Control class, which lets you run things in a control's UI thread.
//If you want to update something on the main thread, from a worker thread... here is howpublic delegate void DelegateCallback(void);public void PerformAction(){  if (InvokeRequired == true)    Invoke(new DelegateCallback(PerformAction));  else    this.myListBox.Items.Add("whatever");}//Note: I just wrote this off the top of my head, so I haven't checked if it compiles.


I think that the purpose behind the async calls is to hide the details of the threads that are created behind the scenes for the async call. So, when the async actually gets around to doing the callback, it does so from the thread where you launched the orignial call.

This topic is closed to new replies.

Advertisement