Tag: async await

自定义TaskScheduler,SynchronizationContext?

async等待演员内部的支持 我将演员lib Akka移植到.NET( https://github.com/rogeralsing/Pigeon )我想在我的演员中添加async / await支持。 这给了我一些问题,因为如果我使用默认调度程序,await continuation将运行与actor并发boundarys相关。 这意味着,当actor处理消息时,可以继续运行,因为这将导致两个线程同时访问actor内部状态。 如果我能以某种方式将任务安排到演员自己的邮箱,并在邮箱运行中完成任务,这将解决问题。 public class SomeActor : UntypedActor { protected override OnReceive(object message) { if (message is SomeMessage) { DoAsyncStuff(); } } private async void DoAsyncStuff() { var res = await something.. //this code will not respect the actor concurrency boundary //since it can run at the […]

保持同步和异步实现

维护方法的同步和异步版本的最佳实践是什么? Let’s suppose we have the following method: public ImportData Import(ZipFile zipFile) { … //Step 1. Initialization var extractedZipContent = zipFile.Extract(); //Step 2 … //Step 3. Some intermediate stuff var parsedData = ParseExtractedZipContent(extractedZipContent); //Step 4 … //Step 5. Some code afterwards } 第2步和第4步是长时间运行的,所以我们想在异步版本的Import方法中异步调用它们: public async Task ImportAsync(ZipFile zipFile) { … //Step 1. Initialization var extractedZipContent […]

使用Visual Studio在代码中查找等待的方法

我有一个问题,在代码中调用async方法而不在它前面await 。 有没有办法找到所有await ? 编辑 – 我特别关注调用多个异步方法的方案(忽略返回值),但只有一个方法await ,这足以使Visual Studio不对其发出警告。

C#httpClient(用于异步调用的块)死锁

现在的情况 有一个客户端通过HttpClient.GetAsync执行get请求。 不幸的是,出于某种原因,我们需要阻止这些电话。 为了做到这一点,使用这个Asynchelper类是为了避免上下文切换死锁(而不仅仅是使用.Result) public static class AsyncHelper { private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default); public static void RunSync(Func func) { AsyncHelper._myTaskFactory .StartNew(func) .Unwrap() .GetAwaiter() .GetResult(); } } 然后实际调用如下所示: AsyncHelper.RunSync(Async Function() Await _httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)) 问题 在使用Netlimiter降低网络速度的压力测试期间,我们遇到了未完成的请求的问题。 例如,当我终止网络连接时(在NetLimiter中),这样的请求将永远留在客户端。 它将保留在AsyncHelper.RunSync调用中,直到它进入httpClient.Timeout。 当连接丢失时,是否应该有一个例外结束此呼叫? 我错过了什么吗?

如何将大量数据传递到我的Web API应用程序?

我在Web API控制器中有这个代码: [Route(“{unit}/{begindate}/{enddate}”)] [HttpPost] public void Post(string unit, string begindate, string enddate, [FromBody] string stringifiedjsondata) { List _produceUsageList = JsonConvert.DeserializeObject<List>(stringifiedjsondata); string _unit = unit; string _begindate = String.Format(“{0}01”, HyphenizeYYYYMM(begindate)); string _enddate = GetEndOfMonthFor(enddate); string appDataFolder = HttpContext.Current.Server.MapPath(“~/App_Data/”); string htmlStr = ConvertProduceUsageListToHtml(_produceUsageList); string htmlFilename = string.Format(“produceUsage_{0}_{1}_{2}.html”, _unit, _begindate, _enddate); string fullPath = Path.Combine(appDataFolder, htmlFilename); File.WriteAllText(fullPath, htmlStr); […]

Task.WhenAll是否在后台线程并行运行任务

以下2个代码片段是否相同? //————————————————– 1. //————————————————– var producer = Task.Run(async () => { await bar.ReadDataAsync(); }); var consumer = Task.Run(async () => { await bar.WriteDataAsync(); }); await Task.WhenAll(consumer, producer); //————————————————– 2. //————————————————– await Task.WhenAll(bar.ReadDataAsync(), bar.WriteDataAsync());

易失性IEnlistmentNotification和TransactionScope.AsyncFlowEnabled = true

除了.NET 4.5.1之外,TransactionScope上还有一个新选项,可以使用异步流。 这允许编写以下客户端代码 using(var txt = new TransactionScope(…, TransactionScopeAsyncFlowOption.Enabled) { await sender.SendAsync(); } 到现在为止还挺好。 但是当我需要实现一个易变的IEnlistmentNotification时,我正在努力做到这一点。 让我们假设以下场景,假设:我的底层基础架构从下到上完全异步 public class MessageSender : ISendMessages { public async Task SendAsync(TransportMessage message, SendOptions options) { await sender.SendAsync(message); } } 所以我想要实现的是引入像这样的易失性IEnlistmentNotification: internal class SendResourceManager : IEnlistmentNotification { private readonly Func onCommit; public SendResourceManager(Func onCommit) { this.onCommit = onCommit; } public void […]

如何正确编写异步方法?

所以我想学习在C#中使用’async’和’await’的基础知识,但我不确定我在这里做错了什么。 我期待以下输出: Calling DoDownload DoDownload done […output here…] 但我没有得到下载的输出,我也期望“完成”,但这需要一段时间。 不应该立即输出吗? 此外,我似乎无法获得字符串结果。 这是我的代码: namespace AsyncTest { class Program { static void Main(string[] args) { Debug.WriteLine(“Calling DoDownload”); DoDownloadAsync(); Debug.WriteLine(“DoDownload done”); } private static async void DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync(“http://www.google.com/”); Debug.WriteLine(txt); } } }

.GetAwaiter()和ConfigureAwait()之间的区别

任何人都可以告诉我GetAwaiter()和ConfigureAwait(false)之间的GetAwaiter() 。 它们都在Async方法中用于解决死锁情况,而ConfigureAwait用于完成任务而不使用Synchrnoization上下文。 我正在寻找可以使用GetAwaiter()和我们使用ConfigureAwait(false)场景。 我听说如果它是我正在构建的库,那么我需要使用ConfigureAwait(false)来生成Await task的Configurable Awaitable对象。 我可以在Unittest案例项目中使用ConfigureAwait ,还是应该使用等待任务的GetAwaiter() 。

在C#中使用generics约束返回Task 的异步方法

我在我正在研究的项目中实现了一个命令模式。 这几乎是当前的结构: public class Response { public bool Success { get; private set; } public static Response CreateErrorResponse() { return new Response { Success = false }; } } public interface ICommand where T : Response { Task ExecuteAsync(); } public abstract CommandBase : ICommand where T: Response { protected abstract Uri BuildUrl(); protected abstract […]