MarioVW
MarioVW

Reputation: 2514

Writing a wrapper for an async method

I have a TransactionOperator class which exposes the following static async method:

public static async Task<bool> ProcessTransactionAsync(Transaction transaction)
{
    var someTransactionOperator = ...; // get appropriate operator
    // some code here
    bool success = await someTransactionOperator.Process(transaction);
    // some more code
    return bool;
}

Now, I want to provide a wrapper instance method in the Transaction class. My question is, which would be the correct/recommended way of writing it? I'm leaning towards #2 because it feels right, but I don't have any supporting arguments for that choice.

// Option 1
public bool ProcessAsync()
{
    return TransactionOperator.ProcessTransactionAsync(this).Result;
}

// Option 2
public Task<bool> ProcessAsync()
{
    return TransactionOperator.ProcessTransactionAsync(this);
}

// Option 3 (compiler warning because there's no 'await' operator)
public async Task<bool> ProcessAsync()
{
    return TransactionOperator.ProcessTransactionAsync(this).Result;
}

// Option 4
public async Task<bool> ProcessAsync()
{
    return await TransactionOperator.ProcessTransactionAsync(this);
}

Upvotes: 2

Views: 1336

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456417

Option 2 is the best option. Option 4 is logically equivalent but has more overhead.

Options 1 and 3 are flat-out wrong. They both block synchronously (even though option 3 is async, it behaves synchronously). Exposing synchronous wrappers for asynchronous methods is not recommended. Among other problems, you can cause deadlocks (as I explain on my blog).

Upvotes: 4

Related Questions