加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如果任务尚未启动,调用Task.wait可能不会等待?

发布时间:2020-12-16 00:10:23 所属栏目:百科 来源:网络整理
导读:我正在通过c#书阅读Jeffrey Richter的clr并感到不舒服,因为任务等待可能并不总是等待我引用 “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 calli
我正在通过c#书阅读Jeffrey Richter的clr并感到不舒服,因为任务等待可能并不总是等待我引用

“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.”

有人可以分享更多的见解,在这种情况下可能会出现这种情况吗?

解决方法

不幸的是,我认为这是措辞.这不是Wait调用在任务完成执行之前返回的;调用Wait的线程可能最终会执行任务本身,而不仅仅是阻塞空闲.

示例代码:

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();
    }
}

每次运行时输出:

DemonstrateIssue thread: 3
Inner task thread: 3

这利用了以下事实:线程池不会根据需要立即启动线程 – 它会等待一段时间以查看现有线程在启动另一个线程之前是否可用.如果你添加Thread.Sleep(5000);在调用task.Wait()之前,您将看到两个任务最终在不同的线程上.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读