[英]Listen(), Task.Run
我是否正確理解每個HandleContextAsync(context))
下面的代碼在新線程中運行? 使用最佳方法限制線程數
private void Listen()
{
while (true)
{
try
{
if (listener.IsListening)
{
var context = listener.GetContext();
sem.WaitOne();
Task.Run(() => HandleContextAsync(context));
}
else
Thread.Sleep(0);
}
}
}
private async Task HandleContextAsync(HttpListenerContext listenerContext)
{
//I process the image received in the request
var iBit = imageBit.Clone(imageInterSect, imageBit.PixelFormat);
iBit.Save(listenerContext.Response.OutputStream, ImageFormat.Png);
listenerContext.Response.ContentType = "image/png";
listenerContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
listenerContext.Response.Close();
}
Task.Run(()=>Action)
基本上創建一個任務,並將任務從線程池分配給某個線程。 所以是的,您是正確的,它在其他線程中運行(但不是新創建的線程)
這是QueueUserWorkItem的編程范例版本的某種程度的靈活性。 目的是-優化資源的使用,因為線程的創建和使用被認為是昂貴的事務,並讓運行時以最佳方式對其進行管理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.