且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#中的任务(异步/等待)循环挡住我的主线程?

更新时间:2023-02-09 18:05:37

Becasue的 Thread.sleep代码

异步/地等待着前两拆你的方法,而之后的await 。上半年你有一个 Thread.sleep代码,导致调用程序线程冻结。

async/await split your method in two, before and after the await. In the first half you have a Thread.Sleep, causing the caller thread to freeze.

使用:

private async Task<PortalODataContext> CallConnection(Connection connection)
{
    bool cancel = false;
    connection.Connected = true;
    var task = getConnection(connection);

    while (!cancel && !task.IsCompleted)
    {
        await Task.Delay(100);

        if (connection.Disconected)
        {
            cancel = true;
        }
    }

    return await task;
}

我不完全相信你正试图在这里实现的目标。

I am not completely sure what you are trying to achieve here.