Description:
How can I use async/await in IHandleMessages.Handle methods without losing context information like IBus.CurrentMessageContext (to use IBus.Reply) or Transaction.Current (the current TransactionScope)?
I already figured out that async void methods won't work because NServiceBus can't know that the message handler hasn't finished yet. Therefore I tried having the async code in a seperate method and calling Task.Wait() in the message handler. This theory was supported by the following post:
https://github.com/Particular/NServiceBus/issues/2220#issuecomment-49273832But even with this method the context is lost after the first await call in the inner method. Sample:
public void Handle(ObjectMessage message)
{
HandleCore(message).Wait();
}
private async Task HandleCore(ObjectMessage message)
{
log.Info("Message received, Returning");
await Task.Delay(100);
bus.Reply(new ObjectResponseMessage());
}
Here both IBus.CurrentMessageContext and Transaction.Current are null after the await call. And therefore the call to IBus.Reply throws an exception with the message "There is no current message being processed".
The only way I found to call async methods in message handlers is to always use Task.Wait or Task.Result instead of await. Is there really no better way? I know that NServiceBus 6 will solve this issue, but I can't upgrade before it is released.