关于WebService异步调用的一点小疑问?
在VS2005中的异步调用,
服务器代码:[code=C#][/code]
[WebMethod]
public string HelloWorld()
{
System.Threading.Thread.Sleep(200);
return "Hello World";
}
客户端异步调用代码:
[code=C#][/code]
private void button1_Click(object sender, EventArgs e)
{
SalesService.WebService service = new SalesClient.SalesService.WebService();
service.HelloWorldCompleted += new SalesClient.SalesService.HelloWorldCompletedEventHandler(service_HelloWorldCompleted);
// do Asyn calling here
service.HelloWorldAsync();
}
private void service_HelloWorldCompleted(object sender, SalesClient.SalesService.HelloWorldCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show(e.Result);
}
else
{
MessageBox.Show(e.Error.Message);
}
}
现在的问题是:当第一次单击Button1的时候,service_HelloWorldCompleted方法调用一次,当第二次单击Button1的时候,service_HelloWorldCompleted方法调用2次,依次类推...我分析可能是:
service.HelloWorldCompleted += new SalesClient.SalesService.HelloWorldCompletedEventHandler(service_HelloWorldCompleted);
这句注册委托有问题,每次都注册,可怎么删除呢?一时想不出好方法呢?TKS
------解决方案--------------------将这句放在全局中:private SalesService.WebService service ;
这两句放在Load里。
service = new SalesClient.SalesService.WebService();
service.HelloWorldCompleted += new SalesClient.SalesService.HelloWorldCompletedEventHandler(service_HelloWorldCompleted);