c# - Making a method asynch -
i have method calls bing api.
ienumerable<webresult> search(string query)
i want make asynchronous if make many calls it, each 1 of calls independant. so, following advice here changed signature
async task<ienumerable<webresult>> searchasynch(string query)
but warning
this async method lacks 'await' operators , run synchronously...
i want entire method asynch (at least that's how think should work). how do that? here's code
public async task<ienumerable<webresult>> searchasynch(string query) { if (query == null) { throw new argumentnullexception("query cannot null"); } dataservicequery<webresult> webquery = _bingcontainer.web(query, null, null, null, null, null, null, null); ienumerable<webresult> webresults = webquery.execute(); return webresults; }
the issue i'm not sure await in code.
the async
keyword doesn't create new asynchronous operation, way of more configuring continuations tasks (i.e. asynchronous operations) exist.
in case, dataservicequery
class provides way asynchronously execute query. unfortunately it's using old async model, not new task
based model, need use task.factory.fromasync
translate it:
public task<ienumerable<webresult>> searchasynch(string query) { dataservicequery<webresult> webquery = _bingcontainer.web(query, null, null, null, null, null, null, null); return task.factory.fromasync(webquery.beginexecute(null, null) , asyncresult => webquery.endexecute(asyncresult))); }
in particular case since don't need other create task don't need async
or await
@ all, can return task constructed. if wanted after got result instead await
task:
public async task<ienumerable<webresult>> searchasynch(string query) { dataservicequery<webresult> webquery = _bingcontainer.web(query, null, null, null, null, null, null, null); var results = await task.factory.fromasync(webquery.beginexecute(null, null) , asyncresult=> webquery.endexecute(asyncresult)); console.writeline("hi there"); return results; }
Comments
Post a Comment