What is the best way to port synchronous code to an asynchronous method

I am creating an application using async-wait methods. But for me there is a big problem with using them. After reading several articles, I still don't know what is the best way to port my heavy synchronization operations to async methods.

I have 2 ideas. Which one is better?

1) Current implementation.

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 use Task.Run and TaskCompletionSource

2) Using only Task.Run without TaskCompletionSource

 private Task<List<UploadedTestModel>> ParseTestFiles(List<string> filesContent) { return Task.Run(() => { . . . . return resultList; }); } 
+7
c # asynchronous task-parallel-library
source share
1 answer

I would not use either one or the other. You will lie to the one who calls your method call. When you set up an asynchronous operation, callers expect it to be naturally asynchronous, that is, there is no thread that it works for.

All of your methods are inherited synchronously, and you must expose them as such. Provide it to the caller to decide if he wants to call them synchronously or use the stream and queue it, do not decide for them.

There is a great article called Should I Expand Asynchronous Wrappers for Synchronous Methods? from Stephan Toub, who talks about all the reasons not to do what you are trying to do, I suggest reading it.

+16
source share

All Articles