The async
keyword doesn't create a new asynchronous operation, it is simply a way of more easily configuring continuations for tasks (i.e. asynchronous operations) that already exist.
In this case, the DataServiceQuery
class already provides a way to asynchronously execute the query. Unfortunately it's using the old async model, not the new Task
based model, so you need to use Task.Factory.FromAsync
to 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 this particular case since you don't need to do anything other than create the task you don't need async
or await
at all, you can just return the task that is constructed. If you wanted to do something after you got the result you could instead await
the 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;
}