Async callbacks in C#

E

eminemabcd

Hi,
I encountered a problem trying to write a code that does the following:

1. Main GUI thread invokes a delegate using BeginInvoke.
2. A secondery thread (from the application's managed thread pool)
starts executing and BeginInvoke returns.
3. Main GUI thread remains responsive while the secondery thread
executes in the background.
4. Secondery thread finishes its execution.
5. Main GUI thread is notified of the completion of the action, and an
event is raised / a callback function executes IN THE MAIN GUI THREAD.

To phase 4 everything works fine; The main thread is responsive and the
secondery thread executes in the background.
Now my problem pops - How can I notify the main thread that the
secondery thread finished its execution, so that it could run a method?
I tried using the callback method parameter of the BeginInvoke method,
but from a little check I performed, it seems that the code executes in
the secondery thread and not in the main GUI thread. If my program was
written in C++, I could have used a window message to notify my main
thread of the completion of the action. The .NET framework does not
contain a PostMessage method to add a message to the main thread's
message pump, and I would really like to avoid using p/invoke. What is
the .NET way to do it?

Many thanks,
John Tiffany.
 
N

Nicholas Paldino [.NET/C# MVP]

John,

In .NET, you would create a delegate that has the signature of the
method that you want to call on the UI thread. Then, from your worker
thread, you would create an instance of that delegate, and pass it to the
BeginInvoke method on a control that was created on that thread, along with
any parameters that are to be passed to the delegate.

The control will make the call to the delegate on the UI thread, and
update it properly.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top