c# - How to return a Task<T> in an async method -
i have method in windows phone 8 app data url
public async static task<byte[]> getdata(string url) { httpclient client = null; httpresponsemessage response = null; stream stream = null; byte[] databytes = null; bool error = false; try { uri uri = new uri(url); client = new httpclient(); response = await client.getasync(uri); response.ensuresuccessstatuscode(); stream = await response.content.readasstreamasync(); databytes = getdatabytes(stream); if (databytes == null) { error = true; } else if (databytes.length == 0) { error = true; } } catch (httprequestexception ) { } if (error) { return getdata(url); // issue } return databytes; }
but since method async one, return type cannot task, have done on line return getdata(url);
since getdata(string)
returns task. ideas on how can rewrite make work?
awaiting result of getdata
may trick. still, recommand rewrite method loop, rather recursively call method again. makes hard read, , may lead unforeseen issues.
public async static task<byte[]> getdata(string url) { bool success = false; byte[] databytes = null; while (!success) { try { uri uri = new uri(url); var client = new httpclient(); var response = await client.getasync(uri); response.ensuresuccessstatuscode(); var stream = await response.content.readasstreamasync(); databytes = getdatabytes(stream); success = databytes != null && databytes.length > 0; } catch (httprequestexception) { } } return databytes; }
Comments
Post a Comment