Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure a new thread is created with Task.Run?

The following code throws an exception 99% of the time.

How can I ensure a new thread is created with Task.Run?

int e;
void Main()
{
    Task.Run(() => 
    {
        e = Thread.CurrentThread.ManagedThreadId;
        Task.Run(() => {CheckThread();}).Wait();
    }).Wait();

    Console.WriteLine("finish");
}

void CheckThread()
{
   if(e == Thread.CurrentThread.ManagedThreadId)
   {
      throw new Exception("Error: " + Thread.CurrentThread.ManagedThreadId);
   }
}
like image 231
user2746029 Avatar asked Sep 29 '17 14:09

user2746029


1 Answers

This code will run the Task code in a new thread

var t = new Task(CheckThread, TaskCreationOptions.LongRunning);
t.Start();
t.Wait();

But please be aware that this is behavior is not documented. So, if you want to be sure you are creating a thread, you must create one yourself

One way to do this, while using a Task to know when the thread has finished

var tcs = new TaskCompletionSource<object>();
var thread = new Thread(() =>
{
    CheckThread();
    tcs.SetResult(null);
} );
thread.Start();
tcs.Task.Wait();
like image 160
Tiago Sousa Avatar answered Oct 12 '22 08:10

Tiago Sousa