如何确保使用Task.Run创建新线程? [英] How to ensure a new thread is created with Task.Run?

查看:706
本文介绍了如何确保使用Task.Run创建新线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码99%的时间抛出异常.

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

如何确保使用Task.Run创建新线程?

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);
   }
}

推荐答案

此代码将在新线程中运行Task代码

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

一种方法,同时使用Task知道线程何时完成

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();

这篇关于如何确保使用Task.Run创建新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆