[英]Cancel HttpClient request on connection lost
在Windows商店項目中,我有以下方法可以上傳文件
public async Task<Boolean> UploadFileStreamService(Stream binaries, String fileName, String filePath)
{
try
{
filePath = Uri.EscapeDataString(filePath);
using (var httpClient = new HttpClient { BaseAddress = Constants.baseAddress })
{
var content = new StreamContent(binaries);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.Current.Resources["token"] as string);
App.Current.Resources["TaskUpload"] = true;
using (var response = await httpClient.PostAsync("file?fileName=" + filePath, content))
{
string responseData = await response.Content.ReadAsStringAsync();
if (responseData.Contains("errorCode"))
throw new Exception("Exception: " + responseData);
else
{
JsonObject jObj = new JsonObject();
JsonObject.TryParse(responseData, out jObj);
if (jObj.ContainsKey("fileId"))
{
if (jObj["fileId"].ValueType != JsonValueType.Null)
{
App.Current.Resources["NewVersionDoc"] = jObj["fileId"].GetString();
}
}
}
return true;
}
}
}
catch (Exception e)
{
...
}
}
在app.xaml.cs上,我在構造函數上有:
NetworkInformation.NetworkStatusChanged +=
NetworkInformation_NetworkStatusChanged; // Listen to connectivity changes
然后用這種方法檢查連接是否更改。
我想知道的是,當我檢測到網絡變化(從有互聯網到沒有互聯網)時,如何停止上傳任務。
您可以使用取消令牌。 您需要CancellationTokenSource
:
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
然后將令牌傳遞到您的UploadFileStreamService
方法(使用_cts.Token
獲取令牌):
public async Task<Boolean> UploadFileStreamService(Stream binaries, String fileName, String filePath, CancellationToken ct)
並使用另一個接受令牌的PostAsync
重載(請注意-如果可能,還對所有其他異步方法(例如ReadAsStringAsync
)使用接受令牌的ReadAsStringAsync
):
using (var response = await httpClient.PostAsync("file?fileName=" + filePath, content, ct))
然后,當您發現網絡連接丟失時,請按以下步驟取消:
_cts.Cancel();
請注意,這將在PostAsync調用上引發OperationCancelledException
,您可能希望(也可能不會)以某種方式處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.