I am trying to launch a thread when an application starts and wait for UI to give it some work without using BackgroundWorker. This thread sleeps when no work is given, and wakes up when the ui asks it do something.
More details:
Simple WPF App: I have a StorageClass to copy files to long term storage. This class is part of the WPF application. When a user clicks a button to store the file to long term storage(Low speed array), I want a thread to copy this file from a highspeed storage array to long term storage. These are large files and I dont want the UI to be blocked. I would like to use one thread that waits for instruction to transfer. Hope this gives more clarity on what I am trying to do.
If you are using .NET 4.0 or above, I’d recommend the TPL over threading directly, and I’d recommend using a
BlockingCollection<T>as a way that the UI can “give some work” via the collection for the consumer to do.The consumer can then be a long-running
Task(again, from the TPL) that consumes from theBlockingCollection<T>, in this way, you don’t need any sleep or manual artifacts like that, theBlockingCollection<T>lets you block on a wait for a given period of time, then resume once an item is ready to consume.So you could define a cancellation token source, blocking collection, and task as:
And your consumer method could be defined as:
Then you’d fire off the task when your form loads by doing:
And then add items by doing:
Where
Transactionis just whatever you define your unit of work to perform…Then, finally, when your application wants to shut down, it can do:
Which tells the consumer that no more items will ever be added to the queue, this will make the
TryTake()returnfalse, and exit the loop since_bin.IsCompletedwill then betrue.Your long running task can then loop on the blocking get until the cancellation token (also TPL) is set to tell it to shut down…