Can't get to the bottom of this one and it's obviously something daft, could anyone help please?
I'm calling a web service asynchronously using a C# console application, and a breakpoint in the 'completed' event is never getting hit.
Here's the example code, really simple:
public static void CallWebservice()
{
try
{
ServiceReference1.GlobalWeatherSoapClient proxy = new GlobalWeatherSoapClient();
proxy.GetCitiesByCountryCompleted += proxy_GetCitiesByCountryCompleted;
proxy.GetCitiesByCountryAsync("France");
}
catch (FaultException faultException)
{
var error = faultException.Message;
}
}
static void proxy_GetCitiesByCountryCompleted(object sender, GetCitiesByCountryCompletedEventArgs e)
{
//Do something here
throw new NotImplementedException();
}
So the breakpoint on the line
throw new NotImplementedException();
is never hit.
However if I add an additional line after the actual asynch call:
System.Threading.Thread.Sleep(5000);
..the breakpoint is now getting hit OK. Can anyone explain what's going on here? Obviously something to do with threads and the debugger, but I don't understand what?
This is because proxy
is going out of scope and so being cleaned up (therefore losing your callback).
So, you need to move your Proxy OUT of the call so that its lifetime is controlled by you:
private ServiceReference1.GlobalWeatherSoapClient _proxy;
public void CallWebservice()
{
try
{
_proxy = new GlobalWeatherSoapClient();
_proxy.GetCitiesByCountryCompleted += proxy_GetCitiesByCountryCompleted;
_proxy.GetCitiesByCountryAsync("France");
}
catch (FaultException faultException)
{
var error = faultException.Message;
}
}
public void proxy_GetCitiesByCountryCompleted(object sender, GetCitiesByCountryCompletedEventArgs e)
{
//Do something here
throw new NotImplementedException();
}
This is not a perfect example as without seeing rest of your code I can't tell you where to instantiate proxy
. Not in CallWebservice
but in a constructor etc but hopefully you get the idea!
您应该等待对proxy.GetCitiesByCountryAsync("France")
的调用,否则您将在函数完成之前退出try块。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.