任务表明IsCompleted,即使它正在等待

时间:2018-03-07 16:05:48

标签: c# task task-parallel-library

我有以下示例代码。问题是,Task表示IsCompleted,即使只是await

longTaskawait s(Task.Delay())尚未完成,为什么IsCompleted为真? longTask无法完成每个while(true),因为它会被static async Task Main(string[] args) { Task longTask = Task.Factory.StartNew(async () => { while (true) { long count = 0; Console.WriteLine("doing hard work."); while (count < 99999999) { count++; } Console.WriteLine("wait for a moment"); await Task.Delay(1000); Console.WriteLine("I have waited enough"); } }); while (true) { Console.WriteLine($"status: {longTask.IsCompleted}"); await Task.Delay(100); } } 捕获?!

{{1}}

preview

1 个答案:

答案 0 :(得分:0)

如果您希望longTask代表内部永不结束的任务,请使用适当的设置调用.Unwrap()或使用具有合理默认值的Task.Run

public static class Program
{
    static async Task Main(string[] args)
    {
        Task longTask = Task.Factory.StartNew(async () =>
        {
            while (true)
            {
                long count = 0;
                Console.WriteLine("doing hard work.");
                while (count < 99999999)
                {
                    count++;
                }
                Console.WriteLine("wait for a moment");
                await Task.Delay(1000);
                Console.WriteLine("I have waited enough");
            }
        }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();
        while (true)
        {
            Console.WriteLine($"status: {longTask.IsCompleted}");
            await Task.Delay(100);
        }

    }
}

public static class Program
{
    static async Task Main(string[] args)
    {
        Task longTask = Task.Run(async () =>
        {
            while (true)
            {
                long count = 0;
                Console.WriteLine("doing hard work.");
                while (count < 99999999)
                {
                    count++;
                }
                Console.WriteLine("wait for a moment");
                await Task.Delay(1000);
                Console.WriteLine("I have waited enough");
            }
        });
        while (true)
        {
            Console.WriteLine($"status: {longTask.IsCompleted}");
            await Task.Delay(100);
        }

    }
}

更多信息:MSDN&amp; Startnew is Dangerous