鉴于以下代码,为什么Task.WhenAny在提供1秒的Task.Delay时永远不会返回?从技术上讲,我不确定它是否会在延长的时间后返回,但是在15秒左右之后我不会手动终止该过程.根据文档,我不需要手动启动delayTask,事实上,如果我尝试手动启动,我会收到异常.
当用户选择WPF应用程序中的上下文菜单项时,将从UI线程调用代码,尽管如果我为上下文菜单项指定了click方法,则在新线程中运行此代码时,它可以正常工作.
public void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
...
SomeMethod();
...
}
public void SomeMethod()
{
...
SomeOtherMethod();
....
}
public void SomeOtherMethod()
{
...
TcpClient client = Connect().Result;
...
}
//In case you're wondering about the override below, these methods are in
//different classes i've just simplified things here a bit so I'm not posting
//pages worth of code.
public override async Task<TcpClient> Connect()
{
...
Task connectTask = tcpClient.ConnectAsync(URI.Host, URI.Port);
Task delayTask = Task.Delay(1000);
if (await Task.WhenAny(connectTask, …Run Code Online (Sandbox Code Playgroud)