Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use await when working with overloads?

I asked myself which of the two following solutions is better?

I have some overloads on a method because the parameters might be optional.

Version 1: Return Tasks and do not await

public class MyClass
    {
        public async Task MyTask(int i, int j, int k)
        {
            try
            {
                await MyStaticClass.MyAsyncWorkIHaveToDo(i, j, k);
            }
            catch (Exception ex)
            {
                // Handle exception
            }
        }

        public Task MyTask(int i, int j)
        {
            int k = 0;
            return MyTask(i, j, k);
        }

        public Task MyTask(int i)
        {
            int j = 1;
            return MyTask(i, j);
        }
    }

Version 2: Await in each method:

public class MyClass2
    {
        public async Task MyTask(int i, int j, int k)
        {
            try
            {
                await MyStaticClass.MyAsyncWorkIHaveToDo(i, j, k);
            }
            catch (Exception ex)
            {
                // Handle exception
            }
        }

        public async Task MyTaskAsync(int i, int j)
        {
            int k = 0;
            await MyTask(i, j, k);
        }

        public async Task MyTaskAsync(int i)
        {
            int j = 1;
            await MyTaskAsync(i, j);
        }
    }

Version 2 generates multiple (3) state machines at IL level. Version 1 generates just one. So I think from a performance point of view, version 1 is better, but there might be some pitfalls I did not think about.

Is there some best practice to follow?

like image 745
VSDekar Avatar asked Jan 28 '26 10:01

VSDekar


1 Answers

Go for version one. As you already said it uses less state machines. You only need await if you do something with the result of the Task or want to handle any exceptions.

edit

You edited the question to include exception handling in the method. That is fine of course and it shows that in such case you have to await the result.

note

I see you are using a static class. Make sure no concurrency issues occur! Do you have any shared state there?

Further reading

Some more background reading can be found here

From that blogpost, when returning a Task directly the attention points are:

  • Exception handling
  • Using the using statement
  • Using AsyncLocal
like image 162
Peter Bons Avatar answered Jan 30 '26 02:01

Peter Bons