gpt4 book ai didi

c# - 使用 Task 异步并等待同步方法

转载 作者:太空宇宙 更新时间:2023-11-03 23:06:36 29 4
gpt4 key购买 nike

我对 async/await 概念还很陌生,所以很抱歉问了一些显而易见的问题。

我需要发送电子邮件,新 API 要求我使用 async 并等待。问题是我的很多方法都需要同步调用这个“发送电子邮件”。

因此,我创建了一个同步包装器方法:

private Task SendEmailAsync(string email, string content)
{
...
...
...
}

private void SendEmail(string email, string content)
{
Task tsk = Task.Factory.StartNew(async () => await SendEmailAsync(email, content));
try { tsk.Wait(); }
catch (AggregateException aex)
{
throw aex.Flatten();
}
}

但出于某种原因,tsk.Wait() 不会等待 await SendEmailAsync(...) 完成。所以,我需要添加 ManualResetEvent。像这样

private void SendEmail(string email, string content)
{
ManualResetEvent mre = new ManualResetEvent(false);
Task tsk = Task.Factory.StartNew(async () =>
{
mre.Reset();
try { await SendEmailAsync(email, content); }
finally { mre.Set(); }
});

mre.WaitOne();
try { tsk.Wait(); }
catch (AggregateException aex)
{
throw aex.Flatten();
}
}

但是 SendEmailAsync(...) 抛出的任何异常都不会被 tsk.Wait() 捕获。我的问题是:

  1. 为什么 tsk.Wait() 不等待 await SendEmailAsync(...)
  2. 如何捕获 await SendEmailAsync(...) 抛出的异常

谢谢!

最佳答案

您可以使用以下扩展以同步方式运行异步代码。

https://stackoverflow.com/a/5097066/5062791

public static class AsyncHelpers
{
/// <summary>
/// Execute's an async Task<T> method which has a void return value synchronously
/// </summary>
/// <param name="task">Task<T> method to execute</param>
public static void RunSync(Func<Task> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
synch.Post(async _ =>
{
try
{
await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();

SynchronizationContext.SetSynchronizationContext(oldContext);
}

/// <summary>
/// Execute's an async Task<T> method which has a T return type synchronously
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="task">Task<T> method to execute</param>
/// <returns></returns>
public static T RunSync<T>(Func<Task<T>> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
T ret = default(T);
synch.Post(async _ =>
{
try
{
ret = await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
return ret;
}

private class ExclusiveSynchronizationContext : SynchronizationContext
{
private bool done;
public Exception InnerException { get; set; }
readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
readonly Queue<Tuple<SendOrPostCallback, object>> items =
new Queue<Tuple<SendOrPostCallback, object>>();

public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("We cannot send to our same thread");
}

public override void Post(SendOrPostCallback d, object state)
{
lock (items)
{
items.Enqueue(Tuple.Create(d, state));
}
workItemsWaiting.Set();
}

public void EndMessageLoop()
{
Post(_ => done = true, null);
}

public void BeginMessageLoop()
{
while (!done)
{
Tuple<SendOrPostCallback, object> task = null;
lock (items)
{
if (items.Count > 0)
{
task = items.Dequeue();
}
}
if (task != null)
{
task.Item1(task.Item2);
if (InnerException != null) // the method threw an exeption
{
throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
}
}
else
{
workItemsWaiting.WaitOne();
}
}
}

public override SynchronizationContext CreateCopy()
{
return this;
}
}
}

关于c# - 使用 Task 异步并等待同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995866/

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