如何记录异步方法的异常?

Şaf*_*Gür 15 .net c# documentation asynchronous

使用XML文档的示例方法:

// summary and param tags are here when you're not looking.
/// <exception cref="ArgumentNullException>
///    <paramref name="text" /> is null.
/// </exception>
public void Write(string text)
{
    if (text == null)
        throw new ArgumentNullException("text", "Text must not be null.");

    // sync stuff...
}
Run Code Online (Sandbox Code Playgroud)

Write(null)按预期抛出异常.这是一个异步方法:

public async Task WriteAsync(string text)
{
    if (text == null)
        throw new ArgumentNullException("text", "Text must not be null.");

    // async stuff...
}
Run Code Online (Sandbox Code Playgroud)

WriteAsync(null),等待之前不会抛出异常.我应该ArgumentNullExceptionexception标签中指定吗?我认为这会让消费者认为调用WriteAsync可能会抛出ArgumentNullException并写下这样的东西:

Task t;
try
{
    t = foo.WriteAsync(text);
}
catch (ArgumentNullException)
{
    // handling stuff.
}
Run Code Online (Sandbox Code Playgroud)

记录异步方法中的异常的最佳实践是什么?

Mar*_*ell 10

不是直接的答案,但我个人建议在这里倾向于快速失败; 这可能意味着编写2种方法:

public Task WriteAsync(string text) // no "async"
{
    // validation
    if (text == null)
        throw new ArgumentNullException("text", "Text must not be null.");

    return WriteAsyncImpl(text);
}
private async Task WriteAsyncImpl(string text)
{
    // async stuff...
}
Run Code Online (Sandbox Code Playgroud)

此模式也是添加"快速路径"代码的理想位置,例如:

public Task WriteAsync(string text) // no "async"
{
    // validation
    if (text == null)
        throw new ArgumentNullException("text", "Text must not be null.");

    if (some condition)
        return Task.FromResult(0); // or similar; also returning a pre-existing
                                   // Task instance can be useful

    return WriteAsyncImpl(text);
}
Run Code Online (Sandbox Code Playgroud)

  • @Killercam我从这个问题中解释了这个例子,我注意到它确实可能不适用于所有情况 - 但是(见上面的评论)我不确定*是*单个答案. (4认同)