C# Call a method in a new thread

I am looking for a way to call a method on a new thread (using C#).

For instance, I would like to call SecondFoo() on a new thread. However, I would then like to have the thread terminated when SecondFoo() finishes.

I have seen several examples of threading in C#, but none that apply to this specific scenario where I need the spawned thread to terminate itself. Is this possible?

How can I force the spawned thread running Secondfoo() to terminate upon completion?

Has anyone come across any examples of this?


Solution 1:

If you actually start a new thread, that thread will terminate when the method finishes:

Thread thread = new Thread(SecondFoo);
thread.Start();

Now SecondFoo will be called in the new thread, and the thread will terminate when it completes.

Did you actually mean that you wanted the thread to terminate when the method in the calling thread completes?

EDIT: Note that starting a thread is a reasonably expensive operation. Do you definitely need a brand new thread rather than using a threadpool thread? Consider using ThreadPool.QueueUserWorkItem or (preferrably, if you're using .NET 4) TaskFactory.StartNew.

Solution 2:

Does it really have to be a thread, or can it be a task too?

if so, the easiest way is:

Task.Factory.StartNew(() => SecondFoo());

Solution 3:

Once a thread is started, it is not necessary to retain a reference to the Thread object. The thread continues to execute until the thread procedure ends.

new Thread(new ThreadStart(SecondFoo)).Start();

Solution 4:

Asynchronous version:

private async Task DoAsync()
{
    await Task.Run(async () =>
    {
        //Do something awaitable here
    });
}