Ş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)
,等待之前不会抛出异常.我应该ArgumentNullException
在exception
标签中指定吗?我认为这会让消费者认为调用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)
归档时间: |
|
查看次数: |
865 次 |
最近记录: |