It takes more than a few seconds for a task to start running

馋奶兔 提交于 2019-12-11 17:42:41

问题


I'm developing an application using WPF and C#. I have the following code:

        var tokenSource = new CancellationTokenSource();
        CancellationToken token = tokenSource.Token;
        Task task = Task.Factory.StartNew(() =>
        {
            // Some action that returns a boolean - **CODE_A**
        }).ContinueWith((task2) =>
        {
                result= task2.Result;
                if (!result)
                {
                    //Another action **CODE_B**
                }
            });

        }, token);

Usually CODE_A starts running immediately, and after less than a second, CODE_B starts executing.

But, sometimes it takes for the task created with Task.Factory.StartNew more than 5 seconds to begin (once it begins, the execution is quick as usual).

I don't understand why does it take so long for the task to start running? Can I somehow influence the task priority, so it would start running immediately in all scenarios? I guess (it is only an assumption) the task is scheduled by the Task scheduler to execute later? Is there a way for me to force the task to run immediately all the time?


回答1:


Tasks are scheduled on the thread pool (by default). If there are lots of other tasks/thread pool usage (and especially if long running tasks are being created but not flagged as such), it can take a while for the thread pool to scale such that a thread is available to execute a newly queued item.

So, I'd look at your system as a whole and see whether you're putting too much work into the thread pool or using it inappropriately.

Can I somehow influence the task priority, so it would start running immediately in all scenarios?

Well, you can manually create threads and take over all usage, but note that even there it's not "immediate". It's as quickly as the OS chooses to schedule any newly created thread.

Or if you truly need code to run "immediately", run it on a thread that you already know is scheduled and running - your own current thread. Of course, then you lose the advantage of asking the TPL to handle the task and just get notified when it's complete. And possible tie up a precious thread such as the UI one.



来源:https://stackoverflow.com/questions/53371150/it-takes-more-than-a-few-seconds-for-a-task-to-start-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!