Skip to content
This repository was archived by the owner on Nov 20, 2018. It is now read-only.

Async APIs should take a CancellationToken #80

Closed
Tratcher opened this issue Jun 20, 2014 · 5 comments
Closed

Async APIs should take a CancellationToken #80

Tratcher opened this issue Jun 20, 2014 · 5 comments

Comments

@Tratcher
Copy link
Member

There are several async APIs in the feature interfaces or on HttpContext that developers may want granular timeout/cancellation support for. Especially anything that can trigger network IO.

Task<X509Certificate> IHttpClientCertificateFeature.GetClientCertificateAsync();
Task<Stream> IHttpOpaqueUpgradeFeature.UpgradeAsync();
Task<WebSocket> IHttpWebSocketFeature.AcceptAsync(IWebSocketAcceptContext context);
Task IAuthenticationHandler.AuthenticateAsync(IAuthenticateContext context);
Task<IReadableStringCollection> IFormFeature.GetFormAsync();
@Tratcher
Copy link
Member Author

We're just doing GetClientCertificateAsync and GetFormAsync for now, as they can require waiting for client data.

AcceptAsync and UpgradeAsync just send response headers, and internally are not even async at the moment.

AuthenticateAsync's work happens mostly on the middleware's return path, not when invoked from app code.

@davidfowl
Copy link
Member

It should be a single optional parameter as well

@Tratcher
Copy link
Member Author

C# won't allow CancellationToken.None as an optional param, optional params must be compile time constants. I've added an overload in the relevant cases.

@Eilon
Copy link
Contributor

Eilon commented Jun 26, 2014

Actually you can with default(CancellationToken) - see the engineering doc.

Relevant section:


Async method patterns

By default all async methods must have the Async suffix. There are some exceptional circumstances where a method name from a previous framework will be grandfathered in.

Passing cancellation tokens is done with an optional parameter with a value of default(CancellationToken), which is equivalent to CancellationToken.None (one of the few places that we use optional parameters). The main exception to this is in web scenarios where there is already an HttpContext being passed around, in which case the context has its own cancellation token that can be used when needed.
Sample async method:

public Task GetDataAsync( 
    QueryParams query, 
    int maxData, 
    CancellationToken cancellationToken = default(CancellationToken)) 
{ 
    ... 
}

@Eilon
Copy link
Contributor

Eilon commented Jun 26, 2014

Oh duh now I see it already in the PR... that's what I get for reading stuff in chronological order...

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants