0

Do I understand correctly that the code below each HandleContextAsync(context)) runs in a new thread? Using the best way to limit the number of threads

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();
}
  • each HandleContextAsync(context)) *can* run in *another* thread. But more important, What does HandleContextAsync do? Does it return Task? then await that one. You are now creating a fire-and-forget task. You'll never know when it is ready and how it finished.. – Peter Bons Feb 04 '18 at 13:13
  • private async Task HandleContextAsync(HttpListenerContext listenerContext) { await new Task(() => { //query context processing}); } – Marty McFly Feb 04 '18 at 13:22
  • So, you do a Task.Run twice? That's not a good idea. Change `Task.Run(() => HandleContextAsync(context));` to `await HandleContextAsync(context)`. Please update the question to include (part of) the code of `HandleContextAsync` – Peter Bons Feb 04 '18 at 13:25
  • @PeterBons Added description HandleContextAsync :) – Marty McFly Feb 05 '18 at 06:21

1 Answers1

0

Task.Run(()=>Action) basically creates a task and task is allocated to some thread from thread pool. So yes, you are correct it runs in a different thread (but not newly created thread)

This is somewhat more flexible programming paradigm version of QueueUserWorkItem. The purpose is - optimize use of resources because thread creation and usage is considered to be costly affair and let runtime manage it in best possible way.

rahulaga-msft
  • 3,964
  • 6
  • 26
  • 44
  • I think 'limit' is not right word here. But yes, I can say to 'optimize and better management of resource' is better to use thread pool. You can see detail explanation here https://stackoverflow.com/questions/230003/thread-vs-threadpool – rahulaga-msft Feb 04 '18 at 13:36
  • My serer will be subject to a heavy load, and it makes no sense to limit the flows? – Marty McFly Feb 04 '18 at 18:14
  • algorithm to create new thread in thread pool is already there in case current numbers of threads in pool doesn't suffice. And it does so based on certain pattern – rahulaga-msft Feb 04 '18 at 18:19
  • The load exceeds the capabilities of the server and the server must work stably – Marty McFly Feb 04 '18 at 18:43
  • if the load exceeds the capabilities you either need to scale up/out or offload the processing job to another process using a message queue for example. – Peter Bons Feb 04 '18 at 18:50
  • @PeterBons I wanted to organize the stability of the server using semaphore or mutex – Marty McFly Feb 05 '18 at 06:22