任务主体不执行

时间:2014-04-08 13:16:07

标签: c# .net multithreading asynchronous task

现在这个让我发疯了。使用.NET Fx 4.0,我有以下延迟机制:

private static Task Delay(double milliseconds)
{
    var tcs = new TaskCompletionSource<bool>();
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Elapsed += (obj, args) => { tcs.TrySetResult(true); };
    timer.Interval = milliseconds;
    timer.AutoReset = false;
    timer.Start();
    return tcs.Task;
}

我在以下代码中调用它:

// delay the execution of SendKey to let the dialog show up
var sendKeyTask = Delay(500).ContinueWith((_) =>
{
    // this gets executed when the dialog is visible
    SendKeys.Send(filePath);
}, TaskScheduler.FromCurrentSynchronizationContext());


MyButton.InvokeMember("click");
sendKeyTask.Wait(3000); //will time out after 3 seconds. 

....

问题是SendKeys.Send(filePath);行永远不会被执行。我错过了什么?

1 个答案:

答案 0 :(得分:0)

@PatrykĆwiek说的是什么 删除Wait(3000),如果您希望在sendKeyTask完成后发生某些事情 - 请继续(或在sendKeyTask中执行此操作,因为它在当前线程上运行)。什么更合适。)