所以我有一个在计算过程中有很长等待时间的函数。我有一个需要调用此函数的端点,但它并不关心函数的完成。
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()
{
}
}
答案 0 :(得分:5)
使用任务并行库(TPL)来剥离新线程。
Task.Run(() => new Repository().computeLongFunction());
return Request.CreateReponse(HttpStatusCode.Ok);
答案 1 :(得分:1)
它看起来不像computeLongFunction()返回任何东西,所以试试这个:
Thread longThread = new Thread(() => new Repository().computeLongFunction());
longThread.Start();
return Request.CreateResponse(HttpStatusCode.Ok);
声明线程,这样你仍然可以控制它的生命周期。