我正在编写一个UWP(WinRT)解决方案,它从服务器下载文件并保存到光盘,同时指示进度。为此,我扩展了IAsyncOperationWithProgress方法。
我的问题在于一行:
private static IAsyncOperationWithProgress<HttpDownloadStatus, DownloadResponse> DownloadAsyncWithProgress(this HttpClient client, HttpRequestMessage request, CancellationToken cancelToken, StorageFile fileToStore)
{
const uint bufferLength = 2048;
var progressResponse = new DownloadResponse
{
File = fileToStore,
DownloadStatus = HttpDownloadStatus.Started,
BytesRecieved = 0,
Progress = 0.00
};
string result = string.Empty;
HttpDownloadStatus returnStatus = HttpDownloadStatus.Busy;
IBuffer streamReadBuffer = new Windows.Storage.Streams.Buffer(bufferLength);
var operation = client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);
return AsyncInfo.Run<HttpDownloadStatus, DownloadResponse>((token, progress) =>
Task.Run(async () =>
{
try
{
if (cancelToken != CancellationToken.None) token = cancelToken;
HttpResponseMessage respMessage;
try
{
respMessage = await operation;
}
catch (Exception ex)
{
throw new Exception("Error sending download request - " + ex.Message);
}
progressResponse.TotalBytes = Convert.ToInt64(respMessage.Content.Headers.ContentLength);
using (var responseStream = await respMessage.Content.ReadAsInputStreamAsync())
{
using (var fileWriteStream = await fileToStore.OpenAsync(FileAccessMode.ReadWrite))
{
token.ThrowIfCancellationRequested();
while ((await responseStream.ReadAsync(streamReadBuffer, bufferLength, InputStreamOptions.None)).Length > 0 && !token.IsCancellationRequested)
{
while(DownloadManager.ShouldPauseDownload && DownloadManager.CurrentDownloadingBook.FileName == fileToStore.Name)
{
if (token.IsCancellationRequested)
break;
}
progressResponse.DownloadStatus = HttpDownloadStatus.Busy;
if (token.IsCancellationRequested)
{
// progressResponse.DownloadStatus = HttpDownloadStatus.Cancelled;
// returnStatus = HttpDownloadStatus.Cancelled;
break;
}
;
await fileWriteStream.WriteAsync(streamReadBuffer);
progressResponse.BytesRecieved += (int)streamReadBuffer.Length;
progressResponse.Progress = (progressResponse.BytesRecieved / (double)progressResponse.TotalBytes) * 100;
//Only give response when close to a byte
if (progressResponse.BytesRecieved % 1048576 == 0)
{
Debug.WriteLine("Should be 1 meg: " + progressResponse.BytesRecieved);
progress.Report(progressResponse);
}
} //while (offset < contentLength);
if (token.IsCancellationRequested)
{
progressResponse.DownloadStatus = HttpDownloadStatus.Cancelled;
returnStatus = HttpDownloadStatus.Cancelled;
}
}
}
if(returnStatus == HttpDownloadStatus.Busy) //only set it if it was still legitimately busy
returnStatus = HttpDownloadStatus.Complete;
return returnStatus;
}
catch (TaskCanceledException tce)
{
Debug.WriteLine("CANCEL - Download cancellation token caught from within task");
return HttpDownloadStatus.Cancelled;
}
}, token));
}
我等待从流中读取内容。如果连接丢失,该线路将无限期地等待,直到重新建立连接。
对于UWP,如何为Http请求分配超时,或者取消单个任务?
我的扩展IAsyncOperationWithProgress:
HttpClient httpClient = new HttpClient(PFilter);
try
{
DownloadResponse downloadResponse = new DownloadResponse { File = fileToSave, DownloadStatus = HttpDownloadStatus.Busy };
CancellationToken cancelToken = m_CancellationSource.Token;
HttpRequestMessage requestMsg = new HttpRequestMessage(HttpMethod.Get, downloadUri);
IAsyncOperationWithProgress<HttpDownloadStatus,DownloadResponse> operationWithProgress = httpClient.DownloadAsyncWithProgress(requestMsg, cancelToken, fileToSave);
operationWithProgress.Progress = new AsyncOperationProgressHandler<HttpDownloadStatus, DownloadResponse>((result, progress) => { progressDelegate(progress); });
var response = await operationWithProgress;
downloadResponse.DownloadStatus = response;
if (response == HttpDownloadStatus.Complete)
{
return HttpWebExceptionResult.Success;
}
else if (response == HttpDownloadStatus.ConnectionLost)
return HttpWebExceptionResult.ConnectionFailure;
else if (response == HttpDownloadStatus.Cancelled)
return HttpWebExceptionResult.RequestCanceled;
else
return HttpWebExceptionResult.UnexpectedError;
}
catch (TaskCanceledException tce)
{
Debug.WriteLine("CANCEL - token caught from StartDownloadAsync ");
return HttpWebExceptionResult.RequestCanceled;
}
catch (Exception ex)
{
return HttpWebExceptionResult.UnexpectedError;
}
如何调用上述代码:
for(int i = 0; i<con.length ; i++){
if(!con[i]) return false;
}
答案 0 :(得分:0)
如果您要从WinRT API取消IAsyncOperation
操作,则需要先将其转换为Task
,然后提供一个CancellationToken
,它将在您的超时持续时间后到期
在此示例中,inputStream.ReadAsync()
如果在2秒内未完成,将被取消:
var timeoutCancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
var response = await inputStream.ReadAsync(buffer, bufferLength, InputStreamOptions.None).AsTask(timeoutCancellationSource.Token);
如果您不想等待2秒钟,则可以随时在Cancel()
上致电CancellationTokenSource
。
timeoutCancellationSource.Cancel();