Jump to content
  • Advertisement
Sign in to follow this  

.NET makeing a worker thread interrupt main thread

This topic is 2283 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Basically I want it to work as follows:

  1. User clicks button
  2. Worker thread spawns
  3. Main GUI keeps running (concurrently)
  4. Worker thread completes and uploads data to main thread
  5. Worker thread terminates
  6. 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 Control.Invoke

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!