Sign in to follow this  

.NET makeing a worker thread interrupt main thread

Recommended Posts

Simple question, Is it possible to have a worker thread interrupt a main thread?

Basically I want it to work as follows:[list=1]
[*]User clicks button
[*]Worker thread spawns
[*]Main GUI keeps running (concurrently)
[*]Worker thread completes and uploads data to main thread
[*]Worker thread terminates
[*]Main GUI displays thread results
I see this type of work done with a substancial amount of programs.
What is the best way to pull this off?

Thanks in advance,


Share this post

Link to post
Share on other sites
See [url=""]Control.Invoke[/url]

Btw, the way that works is by posting a message to the UI thread's message queue which tells it about the delegate to invoke. When the UI thread processes that message it invokes the delegate (thus executing the delegate in the UI thread).

Share this post

Link to post
Share on other sites
I generally use the BackgroundWorker class and hook its DoWork and RunWorkerCompleted events with anonymous methods. DoWork is run on a background thread. RunWorkerCompleted is run on the UI thread.

I put both anonymous methods in a starter method so that they can both capture any local variables declared within the starter method. This lets DoWork generate some data that RunWorkerCompleted has immediate access to once it finishes.

If the DoWork handler needs to report progress to the UI thread or whatever, I use Control.Invoke with another anonymous method or lambda like Washu suggests. This lambda can also capture local variables, which makes everything pretty much magically easy.

I haven't tried the async stuff in C# 5.0 yet, but it's possible that there could be a much easier solution using that.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this