我想通过WebClient异步回调中的ref更新变量。
似乎LIKE
(令牌)中的第二个参数不被ref接受,并且是.DownloadStringAsync()
(e.UserState),所以我没有想法。
那怎么办?
readonly
答案 0 :(得分:0)
作为documentation says,您应该使用System.Net.Http.HttpClient
而不是System.Net.WebClient
(除非您使用的是.NET的旧版本)。
使用HttpClient
,此任务非常简单:
static void Main(string[] args)
{
string a;
using (HttpClient client = new HttpClient())
{
a = client.GetStringAsync("http://someurl.to.json").Result;
}
Console.ReadKey();
Console.WriteLine(a);
}
答案 1 :(得分:0)
您可以使用DownloadStringTaskAsync而不是DownloadStringAsync。
async static Task Main(string[] args)
{
string a = "AAA";
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += Wc_DownloadStringCompleted;
a = await wc.DownloadStringTaskAsync(new Uri("http://someurl.to.json"));
}
Console.ReadKey();
Console.WriteLine(a);
}
private static void Wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// do something with e.result ...;
// update the caller method's 'a' variable (by ref not possible as token) with "BBB"
}
如果您确实要使用DownloadStringAsync
,则可能需要将变量设为全局变量。
或更妙的是,改用HttpClient。 WebClient和HttpWebRequest现在已经很旧了。