gpt4 book ai didi

c# - 发出异步休息请求

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:05 24 4
gpt4 key购买 nike

我正在使用 RestSharp 在 Windows Phone 上发出一些休息请求。

但我正在努力将“Aync/await”与我使用的功能一起使用:

例如这个函数:

   private  void Function() 
{
var client = new RestSharp.RestClient("https://exampleapi.com");
client.Authenticator = [....]
var request = new RestSharp.RestRequest("/example.json", Method.GET);
try
{
client.ExecuteAsync(request, reponse =>
{
if (reponse.StatusCode == HttpStatusCode.OK)
{


// Operations with the json...
}
else
{
MessageBox.Show("Error");
}
});
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}

我试着像这样添加单词 async :

private async void restsharptest() 
{
var client = new RestSharp.RestClient("https://exampleapi.com");
client.Authenticator = [....]
var request = new RestSharp.RestRequest("/example.json", Method.GET);
try
{
client.ExecuteAsync(request, reponse =>
{
if (reponse.StatusCode == HttpStatusCode.OK)
{


var timeline = JsonConvert.DeserializeObject<List<dynamic>>(reponse.Content);
}
else
{
MessageBox.Show("Error");
}
});
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}

但是当我尝试添加 await 时:

var timeline = await  JsonConvert.DeserializeObject<List<dynamic>>(reponse.Content);

我收到以下错误:

Impossible to reach 'System.Collections.Generic.List

和:

Operator 'await' can only be used in a lambda expression async. Mark this with lambda expression modifier 'async'.

如何使用 async/await 我的“Function1”?

编辑:

 client.ExecuteAsync(request, response  =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
List_ = new List<Myobject>();
List_ = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<List<Myobject>>(response.Content));
tcs.SetResult(RefreshList_);
}
else
{
MessageBox.Show("Error");
}
});

我又遇到了这个错误:

Operator 'await' can only be used in a lambda expression async. Mark this with lambda expression modifier 'async'.

我该如何解决这个问题?

最佳答案

要使用异步,您应该执行以下操作:

private async void Function() 
{
var client = new RestSharp.RestClient("https://exampleapi.com");
client.Authenticator = [....]
var request = new RestSharp.RestRequest("/example.json", Method.GET);
try
{
var response = await client.ExecuteTaskAsync(request);

if (reponse.StatusCode == HttpStatusCode.OK)
{
// Operations with the json...
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}

请注意您的 ExecuteAsync 和之前带有 await 的 ExecuteTaskAsync 之间的区别。

关于c# - 发出异步休息请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24984429/

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