问题
I am looking to wrap synchronous methods into asynchronous code in order to expose those methods as asynchronous - the reason is I do not want to duplicate the code inside the synchrnous methods as I would like it to be DRY and already knowing the functionality of the syunchronous code works - no need to manage separate method as well. However I would like asynchronous methods. I understand the purpose of asynchronous methods at least what they do and why I would want to use them.
Consider the following code:
public int AddValues(int a, int b)
{
// some really boring or extremely long DRY method code
return a + b;
}
Adding an Asynchronous Calling Method like below saves time writing code ; Ensures the functionality of the inner code is the same as Synchronous code. Could I or Should I do this?:
public async task AddValuesAsync(int a, int b)
{
return await Task.FromResult(AddValues(a,b));
}
And here is my other question and maybe an answer to me; Calling the Asynch method twice will also call the sync method - and since it is behind the async I can get a cross thread exception ? IS that correct.
So what should I do in this situation - how to keep it DRY and keep it simple? I could make the sync method private and force all calls to the method be Async ..
If you say my example code is a bad way to do it, please give a short reason why and a simple example of a good way to do it ..and any suggestions on what is best and how to do this ?
I have looked here Is wrapping a synchronous call in a Task.Run() to make it asynchronous beneficial? but that does not seem to answer very clearly , what I would like to know.
EDIT
For others who are looking - aside from the answer marked here is info that points to the answer with examples and also more importantly why.
Should I expose asynchronous wrappers for synchronous methods?
Which way is best for wrapping synchronous code into an asynchronous method?
回答1:
I am asking this because I would like to know what the proper way is to make a synchronous methods to have asynchronous versions in a class and as DRY as possible.
The proper way is "don't".
More to the point, your API's shouldn't lie. If they're doing synchronous work, they should have a synchronous signature.
回答2:
After comments by Stephen Cleary I found a link on related.. What is the best way for wrapping synchronous code into asynchronous method
While not worded exactly - one comment included an article link that was worded exactly to one point of my question.
The comment there by Yuval Itzchakov included this. "There is great article called Should I expose asynchronous wrappers for synchronous methods? by Stephan Toub which talks about all the reasons not to do what you're trying to do. I suggest reading it."
来源:https://stackoverflow.com/questions/32639357/wrap-a-synchronous-method-in-asynchronous-call-c-sharp