Reputation: 579
I'm writing a Windows Phone 7 app where one portion of it takes in a URL and checks if the website is still live. The problem is I can't do a return statement inside of the HTTP request and as a result, websites that don't work won't show up as not working in the app.
private string check(string url)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(
new Uri(url));
request.BeginGetResponse(r =>
{
try
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
}
}
catch
{
return "\u2612"; //Error here
}
}, request);
}
catch
{
return "\u2612";
}
return "\u2611";
}
When I try to compile this code, I get these errors:
Error 1 Since 'System.AsyncCallback' returns void, a return keyword must not be followed by an object expression
Error 2 Cannot convert lambda expression to delegate type 'System.AsyncCallback' because some of the return types in the block are not implicitly convertible to the delegate return type
Is there any way around this or some other way to get that return statement to work?
Upvotes: 0
Views: 1317
Reputation: 612
you can use callback result type like this :
private void check(string url, Action<string> act)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(
new Uri(url));
request.BeginGetResponse(r =>
{
try
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
}
}
catch
{
act("\u2612");
}
}, request);
}
catch
{
act(\u2612");
}
act("\u2611"); //may be this call must comment!
}
in anonymous method if you return value it mean that anonymous method will return value not who method called it.
if you write
request.BeginGetResponse(r => {
return "";
}
this mean you pass anonymous method to BeginGetResponse method that has no input parameter and return string parameter.
and BeginGetResponse dos not accept this type of method
UPDATE
and when you want to use :
check(s, (myReturnValue) => {
//myReturnValue is result of method
results.Add(myReturnValue);
//Code in here guaranteed results is filled always...
});
//Code in here is not guaranteed results is filled if you comment code that i suggested, because it fill in callback method and callback method will called in async method...
IMPORTANT
this method will execute async action it mean results.Add(myReturnValue); is not execute exactly after calling check method, because it is async in this way you can not explicitly have return value, and you can use callback method.
if you want execute without async and define explicitly return value for check method you can call GetResponse instead of BeginGetResponse.
Upvotes: 1