Given the following code, why is Task.WhenAny never returned if it is given Task.Delay in 1 second? Technically, I'm not sure that he will be back in some time, but not in 15 seconds, after which I will manually destroy this process. According to the documentation, I will not need to manually start delayTask, and in fact I get an exception if I try to do it manually.
The code is called from the user interface thread when the user selects a context menu item in a WPF application, although it works fine, if I have the click method specified for the context menu item, run this code in a new thread.
public void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
...
SomeMethod();
...
}
public void SomeMethod()
{
...
SomeOtherMethod();
....
}
public void SomeOtherMethod()
{
...
TcpClient client = Connect().Result;
...
}
public override async Task<TcpClient> Connect()
{
...
Task connectTask = tcpClient.ConnectAsync(URI.Host, URI.Port);
Task delayTask = Task.Delay(1000);
if (await Task.WhenAny(connectTask, delayTask) == connectTask)
{
Console.Write("Connected\n");
...
return tcpClient;
}
Console.Write("Timed out\n");
...
return null;
}
ContextMenuItem_Click ,
public void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
...
new Thread(() => SomeMethod()).Start();
...
}