I am trying to return results using async but instead of returning the data I want it returns the entire object
[System.Web.Services.WebMethod(BufferResponse=false)]
public static async Task<bool> getLogin(string username, string password)
{
Login login = new Login();
Task<bool> loginVerify = login.verifyLogin(username,password);
await loginVerify;
return loginVerify.Result;
}
public class Login
{
public async Task<bool> verifyLogin(string username, string password)
{
return true;
}
}
The results from Firefox Firebug show this :
{"d":{"Result":true,"Id":2,"Exception":null,"Status":5,"IsCanceled":false,"IsCompleted":true,"CreationOptions":0,"AsyncState":null,"IsFaulted":false}}
Why isn't it just showing the result?
I tried running
public static async Task<bool> getLogin(string username, string password)
{
Login login = new Login();
Task<bool> loginVerify = login.verifyLogin(username,password);
await loginVerify;
return false;
}
but the firebug report was the same except it said Result false in the json
{"d":{"Result":false,"Id":2,"Exception":null,"Status":5,"IsCanceled":false,"IsCompleted":true,"CreationOptions":0,"AsyncState":null,"IsFaulted":false}}
So my question is why does it show the whole object instead of just the result?
As explained in this answer, WebMethod
does not support async
-await
(it does support another async pattern, APM, and you can convert async
-await
to APM, but it's quite awkward).
So why do you get such weird result? WebMethod
does not know that Task
is some special type, so it treats it just like a regular object, by accessing and serializing its properties. This includes Result
, which synchronously returns the result of the Task
. This also means that the code is not actually asynchronous.