C # /. NET 4.5 - Why is "waiting for Task.WhenAny" never returned if Task.Delay is provided in the WPF application user interface thread?

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;
    ...
}

//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, 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();
    ...
}
+4
1

, Task.Wait Task<T>.Result. , .

, , await ( ) "" async. "" WPF.

, await , WhenAll, WPF. , , . , (.. Wait Result), async .

- await Wait Result. , async, . , , , . , async void - MVVM ( async MVVM MSDN). ; , .

+11

Source: https://habr.com/ru/post/1542851/


All Articles