How to make a method async with async and await?

The reason for async-await is, that whenever your thread has to wait for some other process to finish, your thread can look around to see if it can do something useful instead of waiting idly.

This is especially useful for communication oriented tasks: query data from a database, fetching information from the internet, writing data to a disk, etc. Usually in these cases your thread doesn’t do anything but wait until the other process is completed.

Usually it is not meaningful to use async-await if your thread orders another thread to do some lengthy calculations. The only reason for this would be if the lengthy calculations take a lot of time and you’d like to keep your caller responsive during the calculations. But even then: for the callers of your function it should look similar to calling functions that have a meaningful async-await, like those that fetch data from databases etc.

In your examples it seems like creating the expression is not a lengthy operation. This is usually a very short process. But even if it is a lengthy operation, it is not useful to order a different thread to do the job while your thread is doing nothing.

If the thread is the UI thread, than it could be useful to make your function async, but only if creation of the expression is long enough for the operator to notice the non-responsive UI.

You can make an async version of your GetExpression using Task.Run to call your non-async GetExpression:

async Task<Expression> GetExpressionAsync<T>(ParameterExpression param, Field filter)
{
    return await Task.Run( () => GetExpression(param, filter);
}

Now you can async versions of your other GetExpression functions:

async Task<Expression<Func<T, bool>>> GetExpressionAsync<T>(Field filter)
{
    ParameterExpression param = Expression.Parameter(typeof(T), "t");
    Expression exp = null;
    if (filter != null)
    {
        exp = await GetExpressionAsync<T>(param, filter);
    }
    return Expression.Lambda<Func<T, bool>>(exp, param);
}

But again: it seems that GetExpression is only creating an expression. Before you make an async version of this, you should be sure that it isn’t more expensive to let another thread do this, than to let your thread do it

Leave a Comment