gabba
gabba

Reputation: 2880

How to make partial method async

I have a generated code with partial method

{
    ...
    partial void InterceptOperationCall(IOperationContext context);
    ...

    async Task SomeMethod()
    {
        InterceptOperationCall(cntx);
        await LongOperation(cntx);
    }
}

and handwrited partial

{
    partial void InterceptOperationCall(IOperationContext context)
    {
    }
}

I need to do async calls inside InterceptOperationCall Does any one knows some way to workaround partial method restrictions?

Another words: I want to do InterceptOperationCall asynchronously and guaranteed before long operation, at the same time i want to optionaly declare body of this method in another file.

UPD as workaround solution i chose to:

Any way I keep looking for better solution, and if someone know another ways to provide optional ability to wrap async calls with somoe async logic please help me.

Upvotes: 20

Views: 3961

Answers (3)

Servy
Servy

Reputation: 203837

Partial methods are just like interfaces. They're a contract. Anyone implementing the partial method, just like an interface method, is fulfilling that contract. In this case, the contract of the method is a synchronous method. There's no way to have an asynchronous implementation, because a proper asynchronous implementation of that method requires the caller of the method to know that it's an asynchronous method, and to act accordingly. Since the caller has written the contract as being a synchronous method, that isn't happening.

So your solutions are to change the contract for the method to be asynchronous, meaning changing the partial method's declaration, or to provide a synchronous, rather than asynchronous, implementation.

I suppose a third option would be to have the interface (in this case, partial methods) support both. Have two partial methods, one asynchronous, one synchronous, and let the implementation provide whichever one they want.

Upvotes: -1

Jonas Høgh
Jonas Høgh

Reputation: 10874

I don't see a way around this that doesn't suffer all the drawbacks of async void in general (as discussed in the linked Stephen Cleary article in Peter Schneider's comment)

I think your best bet if you cannot find or write a sync version of the async APIs in question is to call the async methods, then use task.Wait() to wait for completion. If you have multiple async calls, compose them with ContinueWith. Essentially you need to use the Task library in the .Net 4.0 style.

Upvotes: 0

Peter Schneider
Peter Schneider

Reputation: 2939

You can use the async keyword when implementing the partial method.

So

async partial void InterceptOperationCall(IOperationContext context) {

}

should be no problem.

Upvotes: 1

Related Questions