2015年12月7日月曜日

HttpClient, WebClient, WebRequest での CancellationToken によるキャンセル操作のノウハウの寄せ集め。

// --------------------------------
HttpClient after dotNet4.5

http://stackoverflow.com/questions/9746182/where-is-webclient-downloadstringtaskasyncuri-cancellationtoken-in-vs11
c# - Where is WebClient.DownloadStringTaskAsync(Uri,CancellationToken) in VS11 - Stack Overflow

GetAsync(String, CancellarationToken) があるそうです。

でもなぜか、
    var result = await client.GetStringAsync();
ではなく
    var tskRes = client.GetStringAsync();
    while(!tskRes.Wait(TimeSpan.FromSeconds(0.2))) {
        ctoken.ThrowIfCancellarationRequested();
    }
    result = tskRes.Result;
のコードが記載されています。


// --------------------------------
HttpClient after dotNet4.5

http://stackoverflow.com/questions/30053792/async-await-with-cancellationtoken-doesnt-cancel-the-operation
c# - Async/await with CancellationToken doesn't cancel the operation - Stack Overflow

ここでは HttpClient は CancellarationToken が使えるので簡単だよね、となっているようです。


// --------------------------------
WebClient

http://stackoverflow.com/questions/30053792/async-await-with-cancellationtoken-doesnt-cancel-the-operation
c# - Async/await with CancellationToken doesn't cancel the operation - Stack Overflow

WebClient.CancelAsync メソッドで Cancel できるらしい。

    myToken.Register(myWebclient.CancelAsync);
としておくと token で操作可能らしい。


// --------------------------------
WebRequest

http://stackoverflow.com/questions/30053792/async-await-with-cancellationtoken-doesnt-cancel-the-operation
c# - Async/await with CancellationToken doesn't cancel the operation - Stack Overflow

ストリームをコピーするメソッドに token を受け付けるものがある。
ということのようです。
    var stream = response.GetResponseStream()
    var destStream = new MemoryStream()
    await stream.CopyToAsync(destStream, 4096, cancelToken);
    return Encoding.UTF8.GetString(destStream.ToArray());

http://stackoverflow.com/questions/9746182/where-is-webclient-downloadstringtaskasyncuri-cancellationtoken-in-vs11
c# - Where is WebClient.DownloadStringTaskAsync(Uri,CancellationToken) in VS11 - Stack Overflow

ですが、サーバーから待っているときもキャンセルしたいので、
上記のアイデアは使えるかもです。

つまり
    var response = await req.GetResponseAsync();
ではなく
    tskRes = req.GetResponseAsync();
    while(!tskRes.Wait(TimeSpan.FromSeconds(0.2))) {
        ctoken.ThrowIfCancellarationRequested();
    }
    result = tskRes.Result;
のように。


// --------------------------------
WebClient

.NET Framework/WebClientクラスでタイムアウトを変更する

では、継承してタイムアウトを追加する方法が記載されています。


// --------------------------------


0 件のコメント:

コメントを投稿