C# WebAPI线程
所以我有一个函数,它在计算过程中有很长的等待时间。我有一个端点需要调用这个函数,但是它并不关心函数的完成C# WebAPI线程,c#,multithreading,asp.net-web-api,C#,Multithreading,Asp.net Web Api,所以我有一个函数,它在计算过程中有很长的等待时间。我有一个端点需要调用这个函数,但是它并不关心函数的完成 public HttpResponseMessage endPoint { Repository repo= new Repository(); // I want repo.computeLongFunction(); to be called, however this endpoint // can return a http status code "ok"
public HttpResponseMessage endPoint
{
Repository repo= new Repository();
// I want repo.computeLongFunction(); to be called, however this endpoint
// can return a http status code "ok" even if the long function hasn't completed.
repo.computeLongFunction();
return Request.CreateReponse(HttpStatusCode.Ok);
}
// If I make the function async would that work?
public class Repository
{
public void compluteLongFunction()
{
}
}
computeLongFunction()似乎不会返回任何内容,因此请尝试以下方法:
Thread longThread = new Thread(() => new Repository().computeLongFunction());
longThread.Start();
return Request.CreateResponse(HttpStatusCode.Ok);
声明线程,以便您仍然能够控制其生命周期。使用任务并行库(TPL)衍生出一个新线程
Task.Run(() => new Repository().computeLongFunction());
return Request.CreateReponse(HttpStatusCode.Ok);
如果该方法失败会发生什么?有人关心吗?因此,即使调用函数结束,生成的线程也将继续?通过Task.Run剥离一个新任务实际上并不会创建一个新线程。computeLongFunction工作项将计划在资源可用时立即运行。因此,是的,这是一种很好的方法,尤其是在ASP.NET应用程序中运行时;最好避免直接创建线程。您应该尝试创建某种机制,允许用户查看计划任务的完成状态。如果任务失败,它将引发未处理的异常-通常,触发并忘记任务是一种不好的做法。如今,直接与线程交互通常是不受欢迎的——TPL中的线程之上有许多很好的抽象。仍然有直接与线程交互的理由,但它通常属于“仅当您确切知道自己在做什么以及为什么要做”的类别,您可以对任务执行相同的操作-在任务创建时添加LongRunningTask选项