如果任何任务未在一个时间内完成,则c#threads通知用户

时间:2015-12-15 16:03:36

标签: c# wpf multithreading

我有三个任务

        List<Task> TaskList = new List<Task>();
        Stopwatch sw = Stopwatch.StartNew();
        var Task1 = HeavyWorkAsync();
        var Task2 = HeavyWorkAsync();
        var Task3 = HeavyWorkAsync();

        TaskList.Add(Task1);
        TaskList.Add(Task2);
        TaskList.Add(Task3);

如果任何任务在XX秒内没有完成,我想更新我的WPF应用程序上的标签。

我尝试使用WhenAny和WhenAll这样的组合:

Task t = await Task.WhenAny(Task.WhenAll(TaskList), Task.Delay(8000));
label.Content = "Work is still being done";
Console.WriteLine("Regular Stopwatch: {0}", sw.Elapsed.TotalSeconds);

但我不能让它起作用

异步方法:

    private Random m_Random = new Random();

    public void HeavyWork() {
        double secondsToSleep = m_Random.NextDouble() * 10;

        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(secondsToSleep));
    }

    public Task HeavyWorkAsync() {
        return Task.Run(() => HeavyWork());
    }

2 个答案:

答案 0 :(得分:2)

如何使用Task.WaitAll(tasks,10000)?

答案 1 :(得分:1)

您需要先检查哪个任务完成,延迟任务或Task.WhenAll(TaskList)任务(完成所有工作后完成的任务)。这是一个例子:

var delay_task = Task.Delay(8000);
Task t = await Task.WhenAny(Task.WhenAll(TaskList), delay_task);

if (t == delay_task)
{
    label.Content = "Work is still being done";
}
else
{
    //Work finished before the timeout
}