As I develop multiple smaller applications, I notice I could use a new thread here or there for background tasks. I've tried a few options, mainly Background Workers and delegates. What I would like to do is have a dedicated thread class to run all my threads in, that I can re-use throughout multiple programs.
I'm looking for guidance on where to read or look or what I should be doing in this case.
Example of how I fail now:
Main Thread (GUI) starts User clicks button 1 which goes through some logic and starts multiple task intensive calculations (which would freeze the GUI until the calculations complete).
What I'd like to do is something such as..
Main Thread (GUI) starts User clicks button1 which creates threads that enqueue in a list of some sort GUI thread reports progress as threads process calculations Thread finishes and dequeue later on (Potentially?) have thread class looping in the background waiting for an item to enqueue and process as it goes.
My typical method for smaller tasks is
Thread fooThread= new Thread((ThreadStart)delegate
{
//command
});
fooThread.Start();
Problem is, my button events have additional items in them (maybe I should refactor them?)
Sample
private void btnCopy_Click( object sender, EventArgs e )
{
//check file exists, check destination exists, etc
//start new thread
Thread fooThread= new Thread((ThreadStart)delegate
{
//copy files to destination using method foobarCopy(params)
});
fooThread.Start();
//if file copy is successful, inform user on GUI.
}
I am using .NET2.0 mostly, but can bump up to 4.5 as needed.
FileCopier
or whatever with aStart()
. Determining if it's done and notifications are up to you, but that's really your class. I am not sure you need to make your own Thread Manager class, but rather refactoring that code into business objects and from there you can at least see what could be made into a base class for the next one you refactor.