I am writing some new code and would like to write it using async and await, but the calling code does not currently support async. Is it right to write the new code in async and call it sync until the calling code supports async?
Or should I write the code sync and then convert it at a later date? And would it be considered technical debt?
public Result Execute( Paramerters parameters ) {
return ExecuteAsync( parameters ).Result;
}
public Task<Result> ExecuteAsync( Paramerters parameters ) {
...
}
Execute
is on an interface and is called from some other code that is not yet async. Is it correct to create the async version and call it from Execute
until the code calling Execute
is converted to async?
My old code is written in .net 4.5.1 but is not yet converted to async.
3 Answers 3
If you want to call asynchronous code synchronously, you need to handle the synchronization. Only idea I have is that you would block the calling thread till the asynchronous operation finishes. I would consider that extremely dangerous, because it might lead to deadlocks. Especially if you are working in UI, where Tasks are scheduled to run on the UI thread and you would be blocking that exact thread. Example here : Don't Block on Async Code
So I'm for writing synchronous code until you are able to change the caller to asynchronous version.
In any case there is a technical debt, but we must do to lighten the best. better change immediately to async and await
Your code will be somme thing ike this :
public Result Execute(string parameters)
{
Task<Result> task = Task.Run<Result>(async () => await ExecuteAsync());
return task.Result;
}
public async Task<Result> ExecuteAsync(string parameters)
{
Task<Result> result = SomeOtherOperationAsync();
// more code here...
return await result;
}
Hope it helps
Why do you want to make the code asynchronous? If it's because the design requires support for asynchronous calls, then write it using async
/await
. If there's no requirement for the code to be asynchronous, then don't. If requirements change later and require the code to be refactored, then it's not technical debt, it's just adapting to changing requirements. OTOH, if you write it as async and incur overhead to call it synchronously, then that's bad design. Likewise, making code harder to debug and reason about for no reason is also bad design. So unless it's clear your path forward is async, keep it synchronous.
Explore related questions
See similar questions with these tags.
async
andawait
keywords. I'm not sure what you're trying to acomplish