简体   繁体   中英

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

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?

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.

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