如果调用任务尚未开始Task.wait可能不会等待? [英] Calling Task.wait may not wait if the task has not yet started?

查看:248
本文介绍了如果调用任务尚未开始Task.wait可能不会等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过C#电子书阅读杰弗里里希特的CLR和感到很不舒服阅读该任务的等待可能不会总是等待,我引用

I was reading Jeffrey Richter's clr via c# book and felt uncomfortable reading that task wait may not always wait and I quote

当一个线程调用wait方法时,系统会检查任务   该线程等待已开始执行。如果是,则   该线程调用wait会阻塞,直到任务完成   运行。但是,如果任务还没有开始执行尚未,则   系统可以(取决于的TaskScheduler)通过​​执行任务   使用所谓的等待线程。如果发生这种情况,则该线程   呼叫等待,不阻塞;它执行任务并返回   马上。

"When a thread calls the Wait method, the system checks if the Task that the thread is waiting for has started executing. If it has, then the thread calling Wait will block until the Task has completed running. But if the Task has not started executing yet, then the system may (depending on the TaskScheduler ) execute the Task by using the thread that called Wait . If this happens, then the thread calling Wait does not block; it executes the Task and returns immediately."

能否有人请分享更多的见解和在这种情况下可这样的情况可能发生吗?

Can some one please share more insight and in which case can such a scenario may happen?

推荐答案

我觉得这是很不幸的措辞。这并不是说等待任务之前调用返回执行完毕;这是该线程调用等待最终可能执行的任务本身,而不仅仅是阻止袖手旁观。

I think this is unfortunately phrased. It's not that the Wait call returns before the task has finished executing; it's that the thread calling Wait may end up executing the task itself, rather than just blocking idly.

样品code:

using System;
using System.Threading;
using System.Threading.Tasks;

class Test
{
    static void Main()
    {
        // Make sure DemonstrateIssue is already called in a ThreadPool
        // thread...
        Task task = Task.Run((Action) DemonstrateIssue);
        task.Wait();
    }

    static void DemonstrateIssue()
    {
        Console.WriteLine("DemonstrateIssue thread: {0}",
                          Thread.CurrentThread.ManagedThreadId);
        Action action = () => Console.WriteLine("Inner task thread: {0}",
            Thread.CurrentThread.ManagedThreadId);
        Task task = new Task(action);
        // Calling Start will just schedule it... we may be able to Wait
        // before it actually executed
        task.Start();
        task.Wait();
    }
}

输出每次我运行时间:

Output every time I've run it:

DemonstrateIssue thread: 3
Inner task thread: 3

这利用了一个事实,即线程池不运转了线程的马上的需求 - 它会等待一段时间,看看是否在另一个开始之前现有的线程就可以使用了。如果添加的Thread.Sleep(5000); 调用 task.Wait()之前,你会看到这两个任务结束了在不同的线程。

This takes advantage of the fact that the thread pool doesn't spin up threads immediately on demand - it waits for a while to see if an existing thread will become available before starting another one. If you add Thread.Sleep(5000); before the call to task.Wait(), you'll see the two tasks end up on different threads.

这篇关于如果调用任务尚未开始Task.wait可能不会等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆