简体   繁体   English

异步任务配置中未引发异常

[英]Exception not thrown in an async Task configuration

I have the following method 我有以下方法

    public async Task<bool> Connect()
    {
        lock (_connectingLock)
        {
            if (_connecting)
                throw new IOException("Already connecting");
            _connecting = true;
        }

        try {
             await tcpClient.ConnectAsync(...); 
        }           
        catch (SocketException e)
        {
            return false;
        }
        finally
        {
            lock (_connectingLock)
            {
                _connecting = false;
            }
        }
    }

Now, I would expect consecutive calls to Connect() to throw an IOException, but it doesn't happen! 现在,我希望对Connect()连续调用会引发IOException,但是不会发生!

What could be the cause? 可能是什么原因?

Calls to Connect() can't throw exceptions directly. 调用Connect()不能直接引发异常。 Async methods do not throw exceptions. 异步方法不会引发异常。 Instead, they will return tasks which, when awaited, will throw IOException . 相反,它们将返回任务,等待时将抛出IOException (ie the tasks are faulted.) (即任务有故障。)

If that's not what you want, you should separate the calls: 如果这不是您想要的,则应分开调用:

public Task<bool> Connect()
{
    // Eager validation of state...
    lock (_connectingLock)
    {
        if (_connecting)
            throw new IOException("Already connecting");
        _connecting = true;
    }
    return ConnectImpl();
}

private async Task<bool> ConnectImpl()
{
    try {
         await tcpClient.ConnectAsync(...); 
    }           
    catch (SocketException e)
    {
        return false;
    }
    finally
    {
        lock (_connectingLock)
        {
            _connecting = false;
        }
    }
}

It's not clear whether that's appropriate in this case though. 目前尚不清楚在这种情况下是否合适。 It's generally fine to throw things like ArgumentException eagerly, but if the error doesn't represent a bug in the calling code itself, I think returning a faulted task instead is fine. 急于抛出类似ArgumentException东西通常是可以的,但是如果错误不代表调用代码本身中的错误,我认为返回有错误的任务就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM