开发者

Assigning jobs to BackgroundWorker thread one at a time

开发者 https://www.devze.com 2023-04-05 19:40 出处:网络
My silverlight application fetches file sets from a webservice (async). The webservice method accepts an array of file names and returns the set of files (also as an array). The silverlight client mak

My silverlight application fetches file sets from a webservice (async). The webservice method accepts an array of file names and returns the set of files (also as an array). The silverlight client makes several such requests for file sets.

The client issues many requests to the webservice at once. I need a BackgroundWorker thread at the client to process received 开发者_StackOverflow中文版file sets one after the other.

How can I collect all the file sets as and when they receive and give these sets to the BackgroundWorker thread one at a time.

EDIT: I could not run multiple BackgorundWorkers as the file set processing module is not thread-safe.


Use a BlockingCollection / ConcurrentQueue to hold the information about file sets to be processed... in the backgroundworker you just have while loop dequeuing the next file set and processing it... the mentioned collections are threadsafe and really fast since most operations are implemented lock-free...


The backgroundworker has no built-in Listen mechanism. It is supposed to perform a long action and terminate.

One solution could consist in firing up one backgroundworker for each file set.

If the processing of those file sets must be synchronized, you could decide to push each request into a queue (basically an array. Make sure you synchronize access to it). Whenever you backgroundworker is done processing a file set, it would report to the main thread (ProgressChanged event IIRC) and loop over further possible requests in the array. Whenever the array is empty, the worker exits.

Pay attention though: If the worker exits while you are sending a request, you'll have a problem. That's why a basic thread may prove stronger than a background thread, especially if you can't know whether there will be further file sets to process. It all depends on your workflow.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号