gpt4 book ai didi

c# - 如何记录异步方法的异常?

转载 作者:可可西里 更新时间:2023-11-01 08:09:42 25 4
gpt4 key购买 nike

带有 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...
}

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

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

// async stuff...
}

WriteAsync(null),在等待之前不会抛出异常。我应该在 exception 标签中指定 ArgumentNullException 吗?我认为这会让消费者认为调用 WriteAsync 可能会抛出 ArgumentNullException 并编写如下内容:

Task t;
try
{
t = foo.WriteAsync(text);
}
catch (ArgumentNullException)
{
// handling stuff.
}

在异步方法中记录异常的最佳做法是什么?

最佳答案

不是直接的答案,但我个人建议在这里倾向于快速失败;这可能意味着编写 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...
}

此模式也是添加“快速路径”代码的理想场所,例如:

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

关于c# - 如何记录异步方法的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15902645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com