【问题标题】:Unsubscribe handler on Webclient event on C#?在 C# 上的 Webclient 事件上取消订阅处理程序?
【发布时间】:2016-01-25 08:48:03
【问题描述】:

我想实现一个负责将我的 Webclient 订阅到处理程序的方法,当我想取消订阅时,它似乎没有正确完成。 我有一个例子:

我用来订阅的函数

private void SendRequest(Action<object, UploadStringCompletedEventArgs> callback, string url)
{
    if (!wClient.IsBusy)
    {
        wClient.UploadStringCompleted += new UploadStringCompletedEventHandler(callback);
        wClient.UploadStringAsync(new Uri(url), "POST");        
        [...]
    }
}

我的处理程序

private void wClient_request1Completed(object sender, UploadStringCompletedEventArgs e)
{
    wClient.UploadStringCompleted -= wClient_request1Completed;
    [...]
}

private void wClient_request2Completed(object sender, UploadStringCompletedEventArgs e)
{
    wClient.UploadStringCompleted -= wClient_request2Completed;
    [...]
}

我会像这样使用这些方法

private WebClient wClient = new WebClient();

SendRequest(wClient_request1Completed, myUrl1);
// wClient_request1Completed(..) is run successfully

[... Request 1 is already completed ...]

SendRequest(wClient_request2Completed, myUrl2);
// wClient_request1Completed(..) and wClient_request2Completed(..) are run

你知道我的问题吗? 非常感谢!

【问题讨论】:

    标签: c# windows-phone-7 windows-phone-8 webclient


    【解决方案1】:

    这是因为您隐式地创建了一个新委托作为 SendRequest 方法的参数。基本上,您当前的代码可以重写为:

    // Done implicitly by the compiler
    var handler = new Action<object, UploadStringCompletedEventArgs>(wClient_request1Completed); 
    
    wClient.UploadStringCompleted += handler;
    
    // ...
    
    wClient.UploadStringCompleted -= wClient_request1Completed // (instead of handler)
    

    修复它的一种方法是使用UploadStringAsync 方法的有效负载参数来保留对处理程序的引用:

    var handler = new UploadStringCompletedEventHandler(callback);
    wClient.UploadStringCompleted += handler;
    wClient.UploadStringAsync(new Uri(url), "POST", null, handler);        
    

    然后,在UploadStringCompleted 事件中:

    private void wClient_request1Completed(object sender, UploadStringCompletedEventArgs e)
    {
        var handler = (UploadStringCompletedEventHandler)e.UserState;
    
        wClient.UploadStringCompleted -= handler ;
        [...]
    }
    

    也就是说,您应该考虑切换到 HttpClient 和 async/await 编程模型,因为它会使您的代码更容易理解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多