更新时间:2022-06-09 09:32:52
我想使用CancellationToken中止文件下载
I want to use the CancellationToken to abort a file download
下载文件是一项I/O操作,.NET平台上提供了异步可取消(基于I/O完成端口)功能.但是您似乎并没有使用它们.
Downloading a file is an I/O operation, for which asynchronous cancelable (I/O completion port based) functions are available on the .NET platform. Yet you seem to not be using them.
相反,您似乎正在使用 Task.Run
创建(一系列)任务,这些任务执行阻止I/O,其中取消令牌没有传递给 Task中的每个任务.运行
链.
Instead you appear to be creating (a chain of) tasks using Task.Run
that perform blocking I/O, where a cancelation token is not passed on to each task in your Task.Run
chain.
有关进行异步,可等待和可取消的文件下载的示例,请参阅:
For examples of doing async, awaitable and cancelable file downloads, refer to:
HttpClient
:在Windows Phone 8中下载并保存异步文件 WebClient
:具有自己的取消机制:注册方法:
HttpClient
: How to copy HttpContent async and cancelable?WebClient
: Has its own cancellation mechanism: the CancelAsync method, you can connect it to your cancellation token, using the token's Register method:
myToken.Register(myWebclient.CancelAsync);
您可以执行以下操作:
static async Task<string> WsGetResponseString(WebRequest webreq, CancellationToken cancelToken)`
{
cancelToken.Register(webreq.Abort);
using (var response = await webReq.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var destStream = new MemoryStream())
{
await stream.CopyToAsync(destStream, 4096, cancelToken);
return Encoding.UTF8.GetString(destStream.ToArray());
}
}