同步调用异步方法how-would-i-run-an-async-taskt-method-synchronously
同步调用异步方法帮助类:
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;
}
}
}
使用
customerList = AsyncHelpers.RunSync<List<Customer>>(() => GetCustomers());
来源链接
http://social.msdn.microsoft.com/Forums/en/async/thread/163ef755-ff7b-4ea5-b226-bbe8ef5f4796
同步调用异步方法how-would-i-run-an-async-taskt-method-synchronously的更多相关文章
- 尝试解决在构造函数中同步调用Dns.GetHostAddressesAsync()引起的线程死锁
(最终采用的是方法4) 问题详情见:.NET Core中遇到奇怪的线程死锁问题:内存与线程数不停地增长 看看在 Linux 与 Windows 上发生线程死锁的后果. Linux: Microsoft ...
- .NET中如何在同步代码块中调用异步方法
更新记录 本文迁移自Panda666原博客,原发布时间:2021年7月2日. 在同步代码块中调用异步方法,方法有很多. 一.对于有返回值的Task 在同步代码块中直接访问 Task 的 Result ...
- HttpClient中异步方法的同步调用
在System.Net.Http中,提供了使用Http与远程服务器通讯的httpClient,但是里面都是异步方法,有时候我们并不需要使用异步操作.这个时候可以使用如下的方式来进行同步调用. clas ...
- 又踩.NET Core的坑:在同步方法中调用异步方法Wait时发生死锁(deadlock)
之前在将 Memcached 客户端 EnyimMemcached 迁移 .NET Core 时被这个“坑”坑的刻骨铭心(详见以下链接),当时以为只是在构造函数中调用异步方法(注:这里的异步方法都是指 ...
- 委托(delegate)的三种调用方式:同步调用,异步调用,异步回调(转载)
下面为即将被调用的方法: public delegate int AddHandler(int a,int b); public class 加法类 { public static int Add(i ...
- C# 委托的三种调用示例(同步调用 异步调用 异步回调)
首先,通过代码定义一个委托和下面三个示例将要调用的方法: 复制代码 代码如下: public delegate int AddHandler(int a,int b); public class ...
- 似是而非的JS - 异步调用可以转化为同步调用吗?
源起 小飞是一名刚入行前端不久的新人,因为进到了某个大公司,俨然成为了学弟学妹眼中'大神',大家遇到js问题都喜欢问他,这不,此时他的qq弹出了这样一条消息 "hi,大神在吗?我有个问题想问 ...
- 一码阻塞,万码等待:ASP.NET Core 同步方法调用异步方法“死锁”的真相
在我们 2015 年开始的从 .NET Framework 向 .NET Core 迁移的工程中,遇到的最大的坑就是标题中所说的--同步方法中调用异步方法发生"死锁".虽然在 .N ...
- 异步多线程 ASP.NET 同步调用异步 使用Result产生死锁
一个方法调用了async方法,要将这个方法本身设计为async. public class BlogController : Controller { public async Task<Act ...
随机推荐
- BZOJ3253 : 改编
设$f[x][y]$表示从x和y出发相遇的期望长度,则$f[x][x]=0$,且$f[x][y]$对称,共$C(n,2)$个未知量. 列出方程组$G$,得到$G\times F=B$. 高斯消元求出$ ...
- python系统编程(九)
同步的概念 1. 多线程开发可能遇到的问题 假设两个线程t1和t2都要对num=0进行增1运算,t1和t2都各对num修改10次,num的最终的结果应该为20. 但是由于是多线程访问,有可能出现下面情 ...
- shell脚本使用--sleep
#!/bin/bash #filename.sh echo -n Count: tput sc count=; while true; do ]; then let count++; ; tput r ...
- 软件开发 [CJOJ 1101] [NOIP 模拟]
Description 一个软件开发公司同时要开发两个软件,并且要同时交付给用户,现在公司为了尽快完成这一任务,将每个软件划分成m个模块,由公司里的技术人员分工完成,每个技术人员完成同一软件的不同模块 ...
- ggplot2 作图
ggplot2 作图 ggplot2是著名的R语言作图工具包,gg为Grammar of Graphics的缩写,体现了结构化作图的思想.ggplot2根据图层来作图是非常优秀的思想,官方文档在这里 ...
- PAT Basic 1001
1001 害死人不偿命的(3n+1)猜想 (15 分) 卡拉兹(Callatz)猜想: 对任何一个正整数 n,如果它是偶数,那么把它砍掉一半:如果它是奇数,那么把 (3n+1) 砍掉一半.这样一直反复 ...
- Servlet(10)—请求转发和请求重定向
请求转发与请求重定向 ①区别: 本质区别:请求转发只发出一次请求,请求重定向则发出两次请求. 请求转发:地址栏是初次发出请求的地址在最终的Servlet中,request对象和中转的那个request ...
- poj3061 Subsequence(尺取法)
https://vjudge.net/problem/POJ-3061 尺取发,s和t不断推进的算法.因为每一轮s都推进1所以复杂度为O(n) #include<iostream> #in ...
- Unity Inspector面板常用的属性
在扩展Unity的时候,往往会用到一些属性,这里将常用的列一下. 1.属性只读: #if UNITY_EDITOR using UnityEditor; #endif using UnityEngin ...
- 条件式变分自编码机(Conditional Variational Autoencoders)
Conditional Variational Autoencoders 条件式变换自编码机 摘要: Conditional Variational Autoencoders --- 条件式变换自编码 ...