Pergunta

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

enter image description here

Foi útil?

Solução

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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top