当前位置: 首页 > 编程语言 > C#

ErrorWaitingOperator分享

时间:2023-04-11 00:43:31 C#

WaitingOperatorError我的代码有问题。我怎么解决这个问题?这个问题存在于await运算符中。publicMyModel(){HttpClient客户端=newHttpClient();HttpResponseMessageresponse=awaitclient.GetAsync("https://api.vkontakte.ru/method/video.get?uid=219171498&access_token=d61b93dfded2a37dfcfa63779efdb149653292636cac442e53dae9ba6a049a75637143e326cc749");字符串googleSearchText=awaitresponse.Content.ReadAsStringAsync();JObjectgoogleSearch=JObject.Parse(googleSearchText);IListresults=googleSearch["response"].Children().Skip(1).ToList();IListsearchResults=newList();(JTokenresultinresults){MainPage1searchResult=JsonConvert.DeserializeObject(result.ToString());searchResults.Add(searchResult);您正在尝试在构造函数中使用await。你不能那样做——构造函数总是同步的。您只能在方法或匿名函数上使用async和async修饰符;您不能将修饰符应用于构造函数。解决这个问题的一种方法是创建一个静态异步方法来创建一个实例——这将完成所有相关的等待,然后将结果传递给一个简单的同步构造函数。当然,您的调用者需要适当地处理这个问题。publicstaticasyncTaskCreateInstance(){stringgoogleSearchText;使用(HttpClientclient=newHttpClient()){使用(HttpResponseMessageresponse=awaitclient.GetAsync(...)){googleSearchText=awaitresponse.内容。Read;AsStringAsync()}//同步构造函数来完成剩下的工作...returnnewMyModel(googleSearchText);您不能在类的构造函数中使用await。异步方法返回一个可以异步执行的任务对象。构造函数没有返回类型,因此它不能返回Task对象,因此不能等待。这个问题的一个简单解决方案是创建一个Init函数:publicMyModel(){}publicasyncTaskInit(){HttpClientclient=newHttpClient();HttpResponseMessageresponse=awaitclient.GetAsync("https://api.vkontakte.ru/method/video.get?uid=219171498&access_token=d61b93dfded2a37dfcfa63779efdb149653292636cac442e53dae9ba6a049a75637cc143e328");字符串googleSearchText=awaitresponse.Content.ReadAsStringAsync();JObjectgoogleSearch=JObject.Parse(googleSearchText);IListresults=googleSearch["response"].Children().Skip(1).ToList();IListsearchResults=newList();foreach(JTokenresultinresults){MainPage1searchResult=JsonConvert.DeserializeObject(result.ToString());searchResults.Add(searchResult);那么在创建模型的时候:以上就是C#学习教程:等待运算符错误的全部内容。;等待模型.Init();本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: