简体   繁体   中英

Task running few seconds after the call

I have a service that receive messages and sends them to an instance every message i receive i'm sending it to new Task so the operation of process the message will be async

public void ReceiveMessage(string Message) {
      Logger.Logger.Log($"Receive Message {Message} in METHOD method");  
      //see in the log time stamp 12:13:51.000
                Task.Factory.StartNew(() =>
                {
                    Logger.Logger.Log($"Receive Message  {Message} in TASK method"); 
                    //see in the log time stamp 112:13:53.000

                    processMessage(Message);
                });
}

private void processMessage(string message) {
     //do some processing job
}

there are a lot of messages received in the service from different clients , each message is send to different instance , the ReceiveMessage and processMessage are methods per instance So there are 2 seconds delay between calling the method and starting the task - does any one know why this could happens and how to avoid it?

I thought C# is able to manage it's own thread pools...

There is a limited number of Task that can run concurrently, check the property of Task.Factory.Scheduler.MaximumConcurrencyLevel

The default scheduler for the Task Parallel Library and PLINQ uses the .NET Framework thread pool, which is represented by the ThreadPool class, to queue and execute work. The thread pool uses the information that is provided by the Task type to efficiently support the fine-grained parallelism (short-lived units of work) that parallel tasks and queries often represent.

However the ThreadPool pool size depends on several factors:

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

TheadPool - https://msdn.microsoft.com/en-gb/library/system.threading.threadpool.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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