Udostępnij za pośrednictwem


C#: Returning an Object via System.Threading.Tasks.Task

In programming something (in EWS), discovered the joys of what I believe was 'lock contention'. To explain, first we need to cover Tasks.

Async Tasks (which call 'await' against other tasks) will only perform the action requested, if you do not specify a managed object to handle. For example, if I call an async for a string and do not specify that I am expecting an object in return, this is what the code will look like (and will introduce our problem):

string noDataReturns = await System.Threading.Tasks.Task.Run(() => this.GetMeTheStringAsync().Result);

private async Task GetMeTheStringAsync()

{

return await System.Threading.Tasks.Task.Run(() => this.GetMeTheString());

}

private string GetMeTheString()

{

return "This is not the string you're looking for.";

}

If, instead, I tell the task what object I expect to get in return, when the task completes, the result will be object that is passed back - instead of the result of the task:

string dataReturns = await System.Threading.Tasks.Task<string>.Run(() => this.GetMeTheStringAsync().Result);

private async Task<string> GetMeTheStringAsync()

{

return await System.Threading.Tasks.Task<string>.Run(() => GetMeTheString());

}

private string GetMeTheString()

{

return "This is the string you're looking for.";

}

This is probably common-place parlance in the .NET developer's world but I had discovered this when I was spawning a Task that would return a DataTable object but did not specify that I expecting an object in return. As such, the windows form was rendered useless/locked, as I placed the DataTable's data source as the result of the Task but there was no data to put in the data table.