简体   繁体   English

对于 ConfiguredTaskAwaitable,与 Unwrap 等效的是什么?

[英]What's the equivalent to Unwrap for a ConfiguredTaskAwaitable?

I'm creating a (well adapting an existing) helper class to allow me to run async methods synchronously.我正在创建一个(很好地适应现有的)帮助器类,以允许我同步运行async方法。 So far I've got the task factory and a static method that lets me run async methods synchronously as long as I don't configure them with .ConfigureAwait , because .ConfigureAwait turns the return value of the method from a System.Threading.Tasks.Task<T> to a System.Runtime.CompilerServices.ConfiguredTaskAwaitable<T> .到目前为止,我已经有了任务工厂和一个静态方法,只要我不使用.ConfigureAwait配置它们,就可以让我同步运行async方法,因为.ConfigureAwait将方法的返回值从System.Threading.Tasks.Task<T>System.Runtime.CompilerServices.ConfiguredTaskAwaitable<T> The code looks like this:代码如下所示:

public static class AsyncUtils {
    private static readonly TaskFactory _taskFactory =
        new TaskFactory(
            CancellationToken.None,
            TaskCreationOptions.None,
            TaskContinuationOptions.None,
            TaskScheduler.Default
        );

    public static TResult RunSync<TResult>(Func<Task<TResult>> func) {
        return _taskFactory
            .StartNew<Task<TResult>>(func)
            .Unwrap<TResult>()
            .GetAwaiter()
            .GetResult();
    }
}

If I try to add a method to deal with ConfiguredTaskAwaitable<T> , it might look like this:如果我尝试添加一个方法来处理ConfiguredTaskAwaitable<T> ,它可能如下所示:

    public static TResult RunSync<TResult>(Func<ConfiguredTaskAwaitable<TResult>> func) {
        return _taskFactory
            .StartNew<ConfiguredTaskAwaitable<TResult>>(func)
            .Unwrap<TResult>() // Doesn't exist!
            .GetAwaiter()
            .GetResult();
    }

The trouble is, as can be seen from the comment, StartNew<ConfiguredTaskAwaitable> returns a Task<ConfiguredTaskAwaitable<TResult>> instead of a Task<Task<TResult>> meaning that the Unwrap method doesn't exist for it.问题是,从注释中可以看出, StartNew<ConfiguredTaskAwaitable>返回Task<ConfiguredTaskAwaitable<TResult>>而不是Task<Task<TResult>>这意味着不存在Unwrap方法。 Is there an equivalent?有等价物吗? How can I create an equivalent method for ConfiguredTaskAwaitable ?如何为ConfiguredTaskAwaitable创建等效方法?

ConfigureAwait() only controls how the context is resumed after an await . ConfigureAwait()仅控制在await之后如何恢复上下文。 If you're getting the result synchronously, it will have no effect because there is no "resume".如果您同步获取结果,则不会有任何影响,因为没有“简历”。

Additionally, one would typically run async methods synchronously by just doing this:此外,通常只需执行以下操作即可同步运行异步方法:

TResult RunSync<TResult>(Func<Task<TResult>> func) {
    return func().Result;
}

Or this, if you want to force it to run on the thread pool:或者这个,如果你想强制它在线程池上运行:

TResult RunSync<TResult>(Func<Task<TResult>> func) {
    return Task.Run(func).Result;
}

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

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