0

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.

3
  • The code in your button clicks should probably be your class. FileCopier or whatever with a Start(). 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.
    – TyCobb
    Dec 23, 2016 at 23:00
  • 2
    Sounds like you'd be better off using the existing thread pool support. Dec 23, 2016 at 23:13
  • Maybe you should use async callback method to manipulate results for gui or you can use an aspect oriented framework check or control you logic, data etc. like spring.net aop.
    – FreeMan
    Dec 24, 2016 at 1:07

1 Answer 1

0

Upgrade your application to .Net 4.5 and you will be at ease. You will be able to leverage Tasks and Task Parallel Library (TPL) infrastructure with await-async constructs.

In today's era in .Net, you must have really compelling reasons as to why you would create your own threads manually rather than leveraging the existing thread-pool. One such reason could be if you seek absolute control of the new threads which are getting created in your process for the reasons which are mentioned below but are not limited to:

  • When my thread should get created?
  • How many new threads should get created in my process?
  • When my thread should be disposed?
  • What should be the priority of the new thread from OS scheduling algorithm stand-point? e.g. high, medium, low
  • Should my thread be a background thread or a foreground thread?

For typical line of business applications you would hardly need so much of granular control on the threads.

So, Tasks are your best friend to help you to get rid of freezed UI issues. You can have a look at my blog here for more details. Here is how I will rewrite your code:

private async void btnCopy_Click(object sender, EventArgs e)
{
    //check file exists, check destination exists, etc
    string sourceFile = @"C:\a.txt", destinationFile = @"C:\b.txt";
    //Let TPL do the heavy lifting of interacting with disk for I/O
    var copyTask = await CopyFile(sourceFile, destinationFile);

    /* 
    //Manual thread instantiation not needed. Hence commented
    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.
    if (copyTask)
    {
        //show a message box
    }
}

private async Task<bool> CopyFile(string sourceFile, string destinationFile)
{
    bool fileCopiedSuccessfully = true;
    //here use async I/O methods from stream class which support the notion of tasks
    try
    {
        using (FileStream sourceStream = File.Open(sourceFile, FileMode.Open))
        {
            using (FileStream destinationStream = File.Create(destinationFile))
            {
                //exactly at this point of time when the actual copy happens your GUI thread is completely
                //free to do anything. It won't freeze.
                //This work happens on a thread-pool thread which you don't have to worry about.
                await sourceStream.CopyToAsync(destinationStream);
            }
        }
    }
    catch (IOException ioex)
    {
        fileCopiedSuccessfully = false;
        MessageBox.Show("An IOException occured during copy, " + ioex.Message);
    }
    catch (Exception ex)
    {
        fileCopiedSuccessfully = false;
        MessageBox.Show("An Exception occured during copy, " + ex.Message);
    }
    return fileCopiedSuccessfully ;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.