繁体   English   中英

Listen(),Task.Run

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM