问题
I have the following method in my web api controller (the long running methods honor cancellation tokens, i.e. they won't run if cancellation has been requested):
public async Task<IHttpActionResult> ApiMethod(CancellationToken cancellationToken)
{
await LongRunningNetworkOperation1(cancellationToken);
await LongRunningNetworkOperation2(cancellationToken);
return Ok();
}
The client has the following code to call my web api controller:
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMilliseconds(3000);
try
{
// Sending DELETE request
HttpResponseMessage deleteMessage = await httpClient.
DeleteAsync("http://localhost:80/api/apiMethod");
}
catch (Exception e)
{
// Timeout occurred.
}
}
If the client's request times out before "LongRunningNetworkOperation2" is called, will the cancellationToken prevent "LongRunningNetworkOperation2" from running? In other word's, can the client signal the web api to stop running a certain request?
回答1:
can the client signal the web api to stop running a certain request?
In theory, yes. A cancellation of the HttpClient
should close the underlying TCP/IP connection. In response, the ASP.NET stack should detect the loss of its client, and cancel the WebAPI CancellationToken
.
In practice, it depends on how complete the HttpClient
and WebAPI
implementations are that you're using. Cancellation isn't necessarily guaranteed, but I expect it would work at least for the desktop HttpClient
.
来源:https://stackoverflow.com/questions/36586632/can-a-client-cancel-a-web-api-request