[英]How to call asynchronous method from synchronous method in C#?
我有一个public async void Foo()
方法,我想从同步方法调用它。 到目前为止,我从 MSDN 文档中看到的都是通过异步方法调用异步方法,但我的整个程序并不是使用异步方法构建的。
这可能吗?
下面是从异步方法调用这些方法的一个示例:
演练:使用 Async 和 Await(C# 和 Visual Basic)访问 Web
现在我正在研究从同步方法调用这些异步方法。
异步编程确实通过代码库“增长”。 它被比作僵尸病毒。 最好的解决方案是让它增长,但有时这是不可能的。
我在Nito.AsyncEx库中编写了一些类型来处理部分异步代码库。 但是,没有在所有情况下都有效的解决方案。
方案一
如果您有一个不需要同步回其上下文的简单异步方法,那么您可以使用Task.WaitAndUnwrapException
:
var task = MyAsyncMethod();
var result = task.WaitAndUnwrapException();
你不希望使用Task.Wait
或Task.Result
因为包装在异常AggregateException
。
此解决方案仅适用于MyAsyncMethod
不同步回其上下文的情况。 换句话说, MyAsyncMethod
每个await
MyAsyncMethod
应该以ConfigureAwait(false)
结尾。 这意味着它无法更新任何 UI 元素或访问 ASP.NET 请求上下文。
方案B
如果MyAsyncMethod
确实需要同步回其上下文,那么您可以使用AsyncContext.RunTask
来提供嵌套上下文:
var result = AsyncContext.RunTask(MyAsyncMethod).Result;
* 2014 年 4 月 14 日更新:在该库的更新版本中,API 如下:
var result = AsyncContext.Run(MyAsyncMethod);
(这是确定使用Task.Result
在这个例子中,因为RunTask
将传播Task
除外)。
您可能需要AsyncContext.RunTask
而不是Task.WaitAndUnwrapException
的原因是因为在 WinForms/WPF/SL/ASP.NET 上发生了相当微妙的死锁可能性:
Task
。Task
进行阻塞等待。async
方法使用await
而没有ConfigureAwait
。Task
无法完成,因为它只有在async
方法完成时才完成; async
方法无法完成,因为它试图将其延续安排到SynchronizationContext
,并且 WinForms/WPF/SL/ASP.NET 将不允许继续运行,因为同步方法已经在该上下文中运行。 这就是为什么在每个async
方法中尽可能多地使用ConfigureAwait(false)
是个好主意的原因之一。
方案C
AsyncContext.RunTask
不会在每种情况下都有效。 例如,如果async
方法等待一些需要 UI 事件才能完成的事情,那么即使使用嵌套上下文,您也会死锁。 在这种情况下,您可以在线程池上启动async
方法:
var task = Task.Run(async () => await MyAsyncMethod());
var result = task.WaitAndUnwrapException();
但是,此解决方案需要一个将在线程池上下文中工作的MyAsyncMethod
。 因此它无法更新 UI 元素或访问 ASP.NET 请求上下文。 在这种情况下,您也可以将ConfigureAwait(false)
添加到其await
语句中,并使用解决方案 A。
更新,2019 年 5 月 1 日:当前的“最坏做法”在MSDN 文章中。
添加一个最终解决我的问题的解决方案,希望可以节省某人的时间。
首先阅读Stephen Cleary 的几篇文章:
从“不要阻塞异步代码”中的“两个最佳实践”来看,第一个对我不起作用,第二个不适用(基本上,如果我可以使用await
,我会!)。
所以这是我的解决方法:将调用包装在Task.Run<>(async () => await FunctionAsync());
并希望不再陷入僵局。
这是我的代码:
public class LogReader
{
ILogger _logger;
public LogReader(ILogger logger)
{
_logger = logger;
}
public LogEntity GetLog()
{
Task<LogEntity> task = Task.Run<LogEntity>(async () => await GetLogAsync());
return task.Result;
}
public async Task<LogEntity> GetLogAsync()
{
var result = await _logger.GetAsync();
// more code here...
return result as LogEntity;
}
}
Microsoft 构建了一个 AsyncHelper(内部)类来将 Async 作为 Sync 运行。 来源看起来像:
internal static class AsyncHelper
{
private static readonly TaskFactory _myTaskFactory = new
TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return AsyncHelper._myTaskFactory
.StartNew<Task<TResult>>(func)
.Unwrap<TResult>()
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func<Task> func)
{
AsyncHelper._myTaskFactory
.StartNew<Task>(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
}
Microsoft.AspNet.Identity 基类只有 Async 方法,为了将它们称为 Sync,有一些具有扩展方法的类(示例用法):
public static TUser FindById<TUser, TKey>(this UserManager<TUser, TKey> manager, TKey userId) where TUser : class, IUser<TKey> where TKey : IEquatable<TKey>
{
if (manager == null)
{
throw new ArgumentNullException("manager");
}
return AsyncHelper.RunSync<TUser>(() => manager.FindByIdAsync(userId));
}
public static bool IsInRole<TUser, TKey>(this UserManager<TUser, TKey> manager, TKey userId, string role) where TUser : class, IUser<TKey> where TKey : IEquatable<TKey>
{
if (manager == null)
{
throw new ArgumentNullException("manager");
}
return AsyncHelper.RunSync<bool>(() => manager.IsInRoleAsync(userId, role));
}
对于那些关心代码许可条款的人,这里有一个非常相似代码的链接(只是在线程上添加了对文化的支持),其中有注释表明它是由 Microsoft 授权的 MIT 许可。 https://github.com/aspnet/AspNetIdentity/blob/master/src/Microsoft.AspNet.Identity.Core/AsyncHelper.cs
这不是和调用 Task.Run(async ()=> await AsyncFunc()).Result 一样吗? AFAIK,微软现在不鼓励调用 TaskFactory.StartNew,因为它们都是等价的,并且一个比另一个更易读。
绝对不。
简单的答案是
.Unwrap().GetAwaiter().GetResult() != .Result
首先关闭
Task.Result 和 .GetAwaiter.GetResult() 一样吗?
其次.Unwrap()使 Task 的设置不会阻塞包装的任务。
这应该导致任何人问
这不是和调用 Task.Run(async ()=> await AsyncFunc()).GetAwaiter().GetResult() 一样吗
这将是一个It Depends 。
关于 Task.Start() 、 Task.Run() 和 Task.Factory.StartNew() 的使用
摘抄:
Task.Run 使用 TaskCreationOptions.DenyChildAttach 这意味着子任务不能附加到父级,它使用 TaskScheduler.Default 这意味着在线程池上运行任务的将始终用于运行任务。
Task.Factory.StartNew 使用 TaskScheduler.Current 表示当前线程的调度程序,它可能是TaskScheduler.Default 但不总是。
补充阅读:
为了额外的安全,像这样调用它不是更好
AsyncHelper.RunSync(async () => await AsyncMethod().ConfigureAwait(false));
通过这种方式,我们告诉“内部”方法“请不要尝试同步到上层上下文并解除锁定”
非常重要的一点,正如大多数对象架构问题一样,这取决于。
作为一个扩展方法你想使用的功能配置给力,对于绝对每一个电话,或者你让程序员认为自己的异步调用? 我可以看到调用三个场景的用例; 它很可能不是您在 WPF 中想要的东西,在大多数情况下当然是有意义的,但是考虑到 ASP.Net Core 中没有Context,如果您可以保证它是 ASP.Net Core 的内部,那么这无关紧要.
async Main 现在是 C# 7.2 的一部分,可以在项目高级构建设置中启用。
对于 C# < 7.2,正确的方法是:
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
/*await stuff here*/
}
您会在许多 Microsoft 文档中看到这一点,例如: https : //docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-主题订阅
public async Task<string> StartMyTask()
{
await Foo()
// code to execute once foo is done
}
static void Main()
{
var myTask = StartMyTask(); // call your method which will return control once it hits await
// now you can continue executing code here
string result = myTask.Result; // wait for the task to complete to continue
// use result
}
您将 'await' 关键字读作“启动这个长时间运行的任务,然后将控制权返回给调用方法”。 一旦长时间运行的任务完成,它就会执行它之后的代码。 await 之后的代码类似于以前的 CallBack 方法。 最大的区别是逻辑流不会被中断,这使得读写变得更加容易。
我不是 100% 确定,但我相信本博客中描述的技术应该适用于许多情况:
因此,如果您想直接调用此传播逻辑,则可以使用
task.GetAwaiter().GetResult()
。
然而,有一个很好的解决方案(几乎:见评论)适用于每种情况:一个特别的消息泵(SynchronizationContext)。
调用线程将按预期被阻塞,同时仍确保从异步函数调用的所有延续不会死锁,因为它们将被编组到在调用线程上运行的临时 SynchronizationContext(消息泵)。
ad-hoc消息泵助手的代码:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Threading
{
/// <summary>Provides a pump that supports running asynchronous methods on the current thread.</summary>
public static class AsyncPump
{
/// <summary>Runs the specified asynchronous method.</summary>
/// <param name="asyncMethod">The asynchronous method to execute.</param>
public static void Run(Action asyncMethod)
{
if (asyncMethod == null) throw new ArgumentNullException("asyncMethod");
var prevCtx = SynchronizationContext.Current;
try
{
// Establish the new context
var syncCtx = new SingleThreadSynchronizationContext(true);
SynchronizationContext.SetSynchronizationContext(syncCtx);
// Invoke the function
syncCtx.OperationStarted();
asyncMethod();
syncCtx.OperationCompleted();
// Pump continuations and propagate any exceptions
syncCtx.RunOnCurrentThread();
}
finally { SynchronizationContext.SetSynchronizationContext(prevCtx); }
}
/// <summary>Runs the specified asynchronous method.</summary>
/// <param name="asyncMethod">The asynchronous method to execute.</param>
public static void Run(Func<Task> asyncMethod)
{
if (asyncMethod == null) throw new ArgumentNullException("asyncMethod");
var prevCtx = SynchronizationContext.Current;
try
{
// Establish the new context
var syncCtx = new SingleThreadSynchronizationContext(false);
SynchronizationContext.SetSynchronizationContext(syncCtx);
// Invoke the function and alert the context to when it completes
var t = asyncMethod();
if (t == null) throw new InvalidOperationException("No task provided.");
t.ContinueWith(delegate { syncCtx.Complete(); }, TaskScheduler.Default);
// Pump continuations and propagate any exceptions
syncCtx.RunOnCurrentThread();
t.GetAwaiter().GetResult();
}
finally { SynchronizationContext.SetSynchronizationContext(prevCtx); }
}
/// <summary>Runs the specified asynchronous method.</summary>
/// <param name="asyncMethod">The asynchronous method to execute.</param>
public static T Run<T>(Func<Task<T>> asyncMethod)
{
if (asyncMethod == null) throw new ArgumentNullException("asyncMethod");
var prevCtx = SynchronizationContext.Current;
try
{
// Establish the new context
var syncCtx = new SingleThreadSynchronizationContext(false);
SynchronizationContext.SetSynchronizationContext(syncCtx);
// Invoke the function and alert the context to when it completes
var t = asyncMethod();
if (t == null) throw new InvalidOperationException("No task provided.");
t.ContinueWith(delegate { syncCtx.Complete(); }, TaskScheduler.Default);
// Pump continuations and propagate any exceptions
syncCtx.RunOnCurrentThread();
return t.GetAwaiter().GetResult();
}
finally { SynchronizationContext.SetSynchronizationContext(prevCtx); }
}
/// <summary>Provides a SynchronizationContext that's single-threaded.</summary>
private sealed class SingleThreadSynchronizationContext : SynchronizationContext
{
/// <summary>The queue of work items.</summary>
private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> m_queue =
new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>();
/// <summary>The processing thread.</summary>
private readonly Thread m_thread = Thread.CurrentThread;
/// <summary>The number of outstanding operations.</summary>
private int m_operationCount = 0;
/// <summary>Whether to track operations m_operationCount.</summary>
private readonly bool m_trackOperations;
/// <summary>Initializes the context.</summary>
/// <param name="trackOperations">Whether to track operation count.</param>
internal SingleThreadSynchronizationContext(bool trackOperations)
{
m_trackOperations = trackOperations;
}
/// <summary>Dispatches an asynchronous message to the synchronization context.</summary>
/// <param name="d">The System.Threading.SendOrPostCallback delegate to call.</param>
/// <param name="state">The object passed to the delegate.</param>
public override void Post(SendOrPostCallback d, object state)
{
if (d == null) throw new ArgumentNullException("d");
m_queue.Add(new KeyValuePair<SendOrPostCallback, object>(d, state));
}
/// <summary>Not supported.</summary>
public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("Synchronously sending is not supported.");
}
/// <summary>Runs an loop to process all queued work items.</summary>
public void RunOnCurrentThread()
{
foreach (var workItem in m_queue.GetConsumingEnumerable())
workItem.Key(workItem.Value);
}
/// <summary>Notifies the context that no more work will arrive.</summary>
public void Complete() { m_queue.CompleteAdding(); }
/// <summary>Invoked when an async operation is started.</summary>
public override void OperationStarted()
{
if (m_trackOperations)
Interlocked.Increment(ref m_operationCount);
}
/// <summary>Invoked when an async operation is completed.</summary>
public override void OperationCompleted()
{
if (m_trackOperations &&
Interlocked.Decrement(ref m_operationCount) == 0)
Complete();
}
}
}
}
用法:
AsyncPump.Run(() => FooAsync(...));
此处提供了异步泵的更详细说明。
对于任何关注这个问题的人......
如果您查看Microsoft.VisualStudio.Services.WebApi
则有一个名为TaskExtensions
的类。 在该类中,您将看到静态扩展方法Task.SyncResult()
,它就像完全阻塞线程直到任务返回。
它在内部调用task.GetAwaiter().GetResult()
这非常简单,但是它被重载以处理任何返回Task
、 Task<T>
或Task<HttpResponseMessage>
async
方法......语法糖,宝贝......爸爸的爱吃甜食。
看起来...GetAwaiter().GetResult()
是在阻塞上下文中执行异步代码的 MS 官方方法。 对于我的用例来说似乎工作得很好。
var result = Task.Run(async () => await configManager.GetConfigurationAsync()).ConfigureAwait(false);
OpenIdConnectConfiguration config = result.GetAwaiter().GetResult();
或者使用这个:
var result=result.GetAwaiter().GetResult().AccessToken
您可以从同步代码中调用任何异步方法,也就是说,直到您需要await
它们为止,在这种情况下,它们也必须标记为async
。
正如很多人在这里建议的那样,您可以在同步方法中对结果任务调用Wait()
或 Result ,但最终会在该方法中进行阻塞调用,这有点违背了异步的目的。
如果你真的不能让你的方法async
并且你不想锁定同步方法,那么你将不得不通过将它作为参数传递给任务上的ContinueWith()
方法来使用回调方法。
受其他一些答案的启发,我创建了以下简单的辅助方法:
public static TResult RunSync<TResult>(Func<Task<TResult>> method)
{
var task = method();
return task.GetAwaiter().GetResult();
}
public static void RunSync(Func<Task> method)
{
var task = method();
task.GetAwaiter().GetResult();
}
它们可以按如下方式调用(取决于您是否返回值):
RunSync(() => Foo());
var result = RunSync(() => FooWithResult());
请注意,原始问题public async void Foo()
中的签名不正确。 它应该是public async Task Foo()
因为你应该为不返回值的异步方法返回 Task not void (是的,有一些罕见的例外)。
Stephen Cleary 的回答;
该方法不应导致死锁(假设 ProblemMethodAsync 不会将更新发送到 UI 线程或类似的东西)。 它确实假定可以在线程池线程上调用 ProblemMethodAsync,但情况并非总是如此。
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
这是方法;
线程池 Hack 与 Blocking Hack 类似的方法是将异步工作卸载到线程池,然后阻塞生成的任务。 使用此 hack 的代码类似于图 7 中所示的代码。
图 7 线程池 Hack 的代码
C#
public sealed class WebDataService : IDataService
{
public string Get(int id)
{
return Task.Run(() => GetAsync(id)).GetAwaiter().GetResult();
}
public async Task<string> GetAsync(int id)
{
using (var client = new WebClient())
return await client.DownloadStringTaskAsync(
"https://www.example.com/api/values/" + id);
}
}
对 Task.Run 的调用在线程池线程上执行异步方法。 在这里它将在没有上下文的情况下运行,从而避免了死锁。 这种方法的问题之一是异步方法不能依赖于在特定上下文中执行。 因此,它不能使用 UI 元素或 ASP.NET HttpContext.Current。
我知道我来晚了。 但是,如果像我这样的人想要以一种整洁,简单的方式解决此问题,而又不必依赖其他库。
public static class AsyncHelpers
{
private static readonly TaskFactory taskFactory = new
TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
/// <summary>
/// Executes an async Task method which has a void return value synchronously
/// USAGE: AsyncUtil.RunSync(() => AsyncMethod());
/// </summary>
/// <param name="task">Task method to execute</param>
public static void RunSync(Func<Task> task)
=> taskFactory
.StartNew(task)
.Unwrap()
.GetAwaiter()
.GetResult();
/// <summary>
/// Executes an async Task<T> method which has a T return type synchronously
/// USAGE: T result = AsyncUtil.RunSync(() => AsyncMethod<T>());
/// </summary>
/// <typeparam name="TResult">Return Type</typeparam>
/// <param name="task">Task<T> method to execute</param>
/// <returns></returns>
public static TResult RunSync<TResult>(Func<Task<TResult>> task)
=> taskFactory
.StartNew(task)
.Unwrap()
.GetAwaiter()
.GetResult();
}
那么你可以这样称呼它
var t = AsyncUtil.RunSync<T>(() => AsyncMethod<T>());
经过数小时尝试不同的方法,或多或少的成功,这就是我的结局。 在获得结果时它不会以死锁结束,它还会获取并抛出原始异常而不是包装的异常。
private ReturnType RunSync()
{
var task = Task.Run(async () => await myMethodAsync(agency));
if (task.IsFaulted && task.Exception != null)
{
throw task.Exception;
}
return task.Result;
}
这是最简单的解决方案。 我在网上的某个地方看到过,不记得在哪里了,但我一直在成功使用它。 它不会死锁调用线程。
void Synchronous Function()
{
Task.Run(Foo).Wait();
}
string SynchronousFunctionReturnsString()
{
return Task.Run(Foo).Result;
}
string SynchronousFunctionReturnsStringWithParam(int id)
{
return Task.Run(() => Foo(id)).Result;
}
这些 Windows 异步方法有一个漂亮的小方法,称为 AsTask()。 您可以使用它让方法将自身作为任务返回,以便您可以手动调用 Wait() 。
例如,在 Windows Phone 8 Silverlight 应用程序上,您可以执行以下操作:
private void DeleteSynchronous(string path)
{
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Task t = localFolder.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask();
t.Wait();
}
private void FunctionThatNeedsToBeSynchronous()
{
// Do some work here
// ....
// Delete something in storage synchronously
DeleteSynchronous("pathGoesHere");
// Do other work here
// .....
}
希望这可以帮助!
//Example from non UI thread -
private void SaveAssetAsDraft()
{
SaveAssetDataAsDraft();
}
private async Task<bool> SaveAssetDataAsDraft()
{
var id = await _assetServiceManager.SavePendingAssetAsDraft();
return true;
}
//UI Thread -
var result = Task.Run(() => SaveAssetDataAsDraft().Result).Result;
如果你想运行它同步
MethodAsync().RunSynchronously()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.