【问题标题】:C# - updating variable from async method callback BY REF - WebClient classC# - 通过 REF 从异步方法回调更新变量 - WebClient 类
【发布时间】:2019-11-16 20:36:50
【问题描述】:

我想通过 WebClient 异步回调中的 ref 更新变量。

.DownloadStringAsync() (token) 中的第二个参数似乎不被 ref 接受,并且是 readonly (e.UserState) 所以我没有想法。

怎么做?

    static void Main(string[] args)
    {
        string a = "AAA";
        using (WebClient wc = new WebClient())
        {
            wc.DownloadStringCompleted += Wc_DownloadStringCompleted;
            wc.DownloadStringAsync(new Uri("http://someurl.to.json"), a);
        }
        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"
    }

【问题讨论】:

  • 尝试将变量移动到全局范围内。

标签: c# .net asynchronous webclient


【解决方案1】:

作为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);
    }

【讨论】:

    【解决方案2】:

    您可以使用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 的东西现在已经过时了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多