验证异步方法中的参数 [英] Validate parameters in async method

查看:52
本文介绍了验证异步方法中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个具有相同方法的同步和异步版本的类 void MyMethod(对象参数) Task MyMethodAsync(对象参数).在同步版本中,我使用简单的check来验证参数

I'm writing a class which have synchronous and asynchronous versions of the same method void MyMethod(object argument) and Task MyMethodAsync(object argument). In sync version I validate argument with the simple check

if (argument == null)
    throw new ArgumentNullException("argument");

在异步方法中相同的检查应如何显示?

How should the same check look like in async method?

1)与同步方法相同

2)(第一个答案后更新)

2) (Updated after first answer)

if (argument == null)
    return new Task.Factory.StartNew(() => { throw new ArgumentNullException("argument"); });

推荐答案

这在某种程度上取决于您希望何时引发错误-即急切地或作为等待中的一部分.与迭代器块一样,如果要进行急切的错误检查,则需要两种方法,例如:

That depends a bit on when you want the error to be raised - i.e. eagerly, or as part of the awaitable. As with iterator blocks, if you want eager error checks, you need two methods, for example:

public Task<int> SomeMethod(..args..) {
    if(..args fail..) throw new InvalidOperationException(...);
    return SomeMethodImpl(...args...);
}
private async Task<int> SomeMethodImpl(...args...)
{
    ... await etc ...
}

这将在初始调用的一部分中执行所有参数检查 ,而不是等待.如果您希望异常成为可等待的一部分,则可以将其抛出:

This will then perform any argument checking as part of the initial call, not the awaitable. If you want the exception to be part of the awaitable, you can just throw it:

public async Task<int> SomeMethod(..args..) {
    if(..args fail..) throw new InvalidOperationException(...);
    ... await etc ...
}

但是,在您的示例中,您正在返回一个 Task 的事实表明这实际上不是 async 方法,而是是 async (但不是 async )方法.你不能只是做:

However, in your example, the fact that you are returning a Task suggests that this is not actually an async method, but is an async (but not async) method. You can't just do:

return new Task(() => { throw new ArgumentNullException("argument"); });

因为 Task 将永远不会启动-也永远不会启动.我怀疑,您将需要执行以下操作:

because that Task will never have been started - and never will be. I suspect you would need to do something like:

try {
    throw new InvalidArgumentException(...); // need to throw to get stacktrace
} catch(Exception ex) {
    var source = new TaskCompletionSource<int>();
    source.SetException(ex);
    return source.Task;
}

这有点...可能会被更好地封装.这会返回一个 Task ,表明它处于 Faulted 状态.

which is... a bit of a mouthful and could probably be encapsulated a bit better. This will return a Task that indicates it is in the Faulted state.

这篇关于验证异步方法中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆