I am creating an application with using async-await methods. But There is a large problem for me with using them. After reading few articles I still don't know what is the best way for wrapping my heavy sync operations to async methods.
I have 2 ideas. Which one is the best?
1) Current realization.
private Task<List<UploadedTestModel>> ParseTestFiles(List<string> filesContent)
{
var tcs = new TaskCompletionSource<List<UploadedTestModel>>();
Task.Run(() =>
{
var resultList = new List<UploadedTestModel>();
foreach (var testBody in filesContent)
{
try
{
var currentCulture = Thread.CurrentThread.CurrentCulture;
var serializerSettings = new JsonSerializerSettings
{
Culture = currentCulture
};
var parsedData = JsonConvert.DeserializeObject<UploadedTestModel>(testBody, serializerSettings);
resultList.Add(parsedData);
}
catch(Exception exception)
{
tcs.SetException(exception);
}
}
tcs.SetResult(resultList);
});
return tcs.Task;
}
I'm using Task.Run and TaskCompletionSource
2) Using only Task.Run without TaskCompletionSource
private Task<List<UploadedTestModel>> ParseTestFiles(List<string> filesContent)
{
return Task.Run(() =>
{
. . . .
return resultList;
});
}