Ames ISU
Ames ISU

Reputation: 407

Is it a good practice to start a new thread in a method

I have a class defined as follows, the Stop() function just wants to see whether the data is saved or not. If it's saved, then it deletes the data, otherwise, it starts a new thread to save the data (because the data might be very big, and costs much time to save). I wonder whether it's a good practice to start a new thread like this. If exception happens in the thread, how could I handle it? If the save takes a long time, what will happen if the user close the application? It doesn't seem to be a good practice for me, but I don't know whether I'm correct. If it's not good, what could be a better way to do it? Thanks!

public class AHelperClass
    {
        public void Stop()
        {                
            if (IsDataSaved)
            {
                DeleteData();
            }
            else
            {
                Thread aThread = new Thread(() => SaveData());
                aThread.Name = "Saving Thread";
                aThread.Start();
            }
        }
    }

Upvotes: 0

Views: 678

Answers (2)

Eric J.
Eric J.

Reputation: 150138

Is it a good practice to start a new thread in a method

That depends.

If your application uses a UI framework such as WinForms or WPF that relies on one thread remaining unblocked to process UI events, then yes, do not use the UI thread to perform any operation longer than an acceptable delay to the responsiveness of your UI. You can accomplish this with the async/await pattern (best suited for IO, as in your case), or by starting multiple threads / Tasks for CPU intensive work.

In a web service / controller, it is generally unwise to start a new thread. Instead, use the async/await pattern to perform IO intensive tasks.

If your work is CPU intensive (not your case here), regardless of the application type, it can be a good idea to create multiple threads and split work between the threads to maximize use of multiple CPU cores.

Rather than working with Threads directly, if you do start your own, it is probably wiser to work with Tasks. See Task vs Thread differences

Upvotes: 2

Jakub Lortz
Jakub Lortz

Reputation: 14894

Creating a new thread is expensive, and the CPU can only process one thread per core at a time. It's better to let the ThreadPool manage threads for you.

You should only use new Thread() if you need to control the way the thread is created (for example if you need a foreground thread, or a thread with specific priority).

The easiest way to perform a CPU-intensive operation on a background thread is to use Task.Run(). Internally. it will use the ThreadPool.

For I/O operations, use async versions of the I/O methods. This way you will not block a thread waiting for the I/O.

You can await a task to get the result and to catch exceptions without blocking your main thread.

Upvotes: 0

Related Questions