How to Invoke on background thread

2019-08-23 14:57发布

问题:

Is there a way to invoke a method on a background thread ?

I am aware of BackgroundWorker/Creating a thread or use ThreadPool.QueueUserWorkItem etc but that's not the answer i am looking for

for e.g. the SCSF has attributes to ensure the method is invoked on a background or a UI thread

I'd like to do something similar for a small app and am looking for a working example

回答1:

I think the BackgroundWorker will fit your needs. It allows you to run an operation in the background in a Winform app. Those articles have working examples. :)



回答2:

There are many ways to invoke a method on a background thread.

Do you want to block while the method is running? Do you want a result returned from the method? Do you want this result displayed in the UI? Is the method called only once? Many times, as needed? Many times in a loop? Asynchronously? Should the background thread continue if your app quits? The answer to these questions will tell you which method you should use.

You can get an overview of the various thread message passing methods from a great article at The Code Project.



回答3:

Thread pool already uses background threads. However, you don't have any control over those threads. If you want control, then you need to use System.Threading.Thread. This gives you more control over how a thread is created (background, foreground, etc) and managed (suspend, resume, sleep, etc).