本文介绍了我如何从非异步方法调用异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有以下方法: 公共字符串RetrieveHolidayDatesFromSource(){        VAR的结果= this.RetrieveHolidayDatesFromSourceAsync();        /** 做东西 **/        VAR returnedResult = this.TransformResults(result.Result); / **凡结果被使用** /        返回returnedResult;    }    私人异步任务&LT;串GT; RetrieveHolidayDatesFromSourceAsync(){        使用(VAR的HttpClient =新的HttpClient()){            VAR JSON =等待httpClient.GetStringAsync(SourceURI);            返回JSON;        }    } 以上不工作,似乎无法正常返回任何结果。我不知道我在哪里丢失的一份声明中强制结果的的await?我想RetrieveHolidayDatesFromSource()方法返回一个字符串。 下面的工作正常,但它是同步的,我相信它可以改进?请注意,以下是同步的,我想更改为异步但我无法绕到我的头出于某种原因。 公共字符串RetrieveHolidayDatesFromSource(){        VAR的结果= this.RetrieveHolidayDatesFromSourceAsync();        /** 做东西 **/        VAR returnedResult = this.TransformResults(结果); / **这是结果实际使用** /        返回returnedResult;    }    私人字符串RetrieveHolidayDatesFromSourceAsync(){        使用(VAR的HttpClient =新的HttpClient()){            VAR JSON = httpClient.GetStringAsync(SourceURI);            返回json.Result;        }    } 我缺少的东西吗? 请注意:由于某些原因,当我断点上述异步方法,当它到达行VAR JSON =等待httpClient.GetStringAsync(SourceURI),它只是出去断点,我不能再进去方法。解决方案 Yes. Asynchronous code - by its nature - implies that the current thread is not used while the operation is in progress. Synchronous code - by its nature - implies that the current thread is blocked while the operation is in progress. This is why calling asynchronous code from synchronous code literally doesn't even make sense. In fact, as I describe on my blog, a naive approach (using Result/Wait) can easily result in deadlocks.The first thing to consider is: should my API be synchronous or asynchronous? If it deals with I/O (as in this example), it should be asynchronous. So, this would be a more appropriate design:public async Task<string> RetrieveHolidayDatesFromSourceAsync() { var result = await this.DoRetrieveHolidayDatesFromSourceAsync(); /** Do stuff **/ var returnedResult = this.TransformResults(result); /** Where result gets used **/ return returnedResult;}As I describe in my async best practices article, you should go "async all the way". If you don't, you won't get any benefit out of async anyway, so why bother?But let's say that you're interested in eventually going async, but right now you can't change everything, you just want to change part of your app. That's a pretty common situation.In that case, the proper approach is to expose both synchronous and asynchronous APIs. Eventually, after all the other code is upgraded, the synchronous APIs can be removed. I explore a variety of options for this kind of scenario in my article on brownfield async development; my personal favorite is the "bool parameter hack", which would look like this:public string RetrieveHolidayDatesFromSource() { return this.DoRetrieveHolidayDatesFromSourceAsync(sync: true).GetAwaiter().GetResult();}public Task<string> RetrieveHolidayDatesFromSourceAsync() { return this.DoRetrieveHolidayDatesFromSourceAsync(sync: false);}private async Task<string> DoRetrieveHolidayDatesFromSourceAsync(bool sync) { var result = await this.GetHolidayDatesAsync(sync); /** Do stuff **/ var returnedResult = this.TransformResults(result); return returnedResult;}private async Task<string> GetHolidayDatesAsync(bool sync) { using (var client = new WebClient()) { return sync ? client.DownloadString(SourceURI) : await client.DownloadStringTaskAsync(SourceURI); }}This approach avoids code duplication and also avoids any deadlock or reentrancy problems common with other "sync-over-async" antipattern solutions.Note that I would still treat the resulting code as an "intermediate step" on the path to a properly-asynchronous API. In particular, the inner code had to fall back on WebClient (which supports both sync and async) instead of the preferred HttpClient (which only supports async). Once all the calling code is changed to use RetrieveHolidayDatesFromSourceAsync and not RetrieveHolidayDatesFromSource, then I'd revisit this and remove all the tech debt, changing it to use HttpClient and be async-only. 这篇关于我如何从非异步方法调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-26 06:10