AsTask doesn't exist to implement a cancellation timeout for Async Read

余生长醉 提交于 2019-12-08 07:34:05

问题


I am eager to add a time-out feature to my stream.ReadAsync() and read Microsoft help in this article Async Cancellation: Bridging between the .NET Framework and the Windows Runtime (C# and Visual Basic). This article suggests to use AsTask() to make this happen. However my C# doesn't seem to recognize AsTask() at all.

I am using Visual Studio 2013 with Windows 7 along with using System.Threading; and this is the piece of code I have:

private async Task<int> ReadAsync(BluetoothClient Client)
{
    const int timeoutMs = 10000;
    var cancelationToken = new CancellationTokenSource(timeoutMs);


    var stream = Client.GetStream();
    byte[] buffer = { 0 };
    int offset = 0;
    int count = 1;
    StatusManager("~Async Read Started...");

    //This line works perfectly fine.
    var rx = await stream.ReadAsync(buffer, offset, count);
    //This line gets underlined with error for AsTask()
    var rx = await stream.ReadAsync(buffer, offset, count).AsTask(cancelationToken);
    //rx.AsTask().Start();
    StatusManager("Recieved byte " + rx.ToString());
    StatusManager("~Async Read Finished.");
}

What am I missing here folks. I am puzzled :)

UPDATE: These are the list of .NET packages installed and I would say Visual Studio 2013 uses 4.5


回答1:


As @Noseratio commented, the AsTask in the linked article is for WinRT asynchronous operations, not BCL types.

In your case, you can just pass the cancellation token directly to the method:

var cancelationToken = new CancellationTokenSource(timeoutMs).Token;
...
var rx = await stream.ReadAsync(buffer, offset, count, cancellationToken);


来源:https://stackoverflow.com/questions/22775015/astask-doesnt-exist-to-implement-a-cancellation-timeout-for-async-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!