取消订阅C#上Webclient事件的处理程序?

取消订阅C#上Webclient事件的处理程序?,c#,windows-phone-7,windows-phone-8,webclient,C#,Windows Phone 7,Windows Phone 8,Webclient,我想实现一个方法,负责将我的Webclient订阅给处理程序,当我想取消订阅时,它似乎没有正确完成。 我举一个例子: 我的功能是订阅 private void SendRequest(Action<object, UploadStringCompletedEventArgs> callback, string url) { if (!wClient.IsBusy) { wClient.UploadStringCompleted += new Uploa

我想实现一个方法,负责将我的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 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
你知道我的问题吗?
多谢各位

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

// Done implicitly by the compiler
var handler = new Action<object, UploadStringCompletedEventArgs>(wClient_request1Completed); 

wClient.UploadStringCompleted += handler;

// ...

wClient.UploadStringCompleted -= wClient_request1Completed // (instead of handler)
然后,在
UploadStringCompleted
事件中:

private void wClient_request1Completed(object sender, UploadStringCompletedEventArgs e)
{
    var handler = (UploadStringCompletedEventHandler)e.UserState;

    wClient.UploadStringCompleted -= handler ;
    [...]
}

这样说,你应该考虑切换到“代码> HTTPcli客< /COD>”和“异步/等待编程模型”,因为这将使你的代码更容易理解。

var handler = new UploadStringCompletedEventHandler(callback);
wClient.UploadStringCompleted += handler;
wClient.UploadStringAsync(new Uri(url), "POST", null, handler);        
private void wClient_request1Completed(object sender, UploadStringCompletedEventArgs e)
{
    var handler = (UploadStringCompletedEventHandler)e.UserState;

    wClient.UploadStringCompleted -= handler ;
    [...]
}