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);
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With