我很想在我的stream.ReadAsync()
添加超时功能,并在本文Async Cancellation: Bridging between the .NET Framework and the Windows Runtime (C# and Visual Basic)中阅读Microsoft帮助。本文建议使用AsTask()
来实现这一目标。但是我的C#似乎根本不会识别AsTask()
。
我正在使用 Visual Studio 2013 与 Windows 7 以及using System.Threading;
,这是我的代码:
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.");
}
我在这里想念的是什么。我很困惑:)
更新:这些是安装的.NET软件包列表,我会说Visual Studio 2013使用4.5
答案 0 :(得分:3)
正如@Noseratio评论的那样,链接文章中的AsTask
用于WinRT异步操作,而不是BCL类型。
在您的情况下,您可以直接将取消令牌传递给方法:
var cancelationToken = new CancellationTokenSource(timeoutMs).Token;
...
var rx = await stream.ReadAsync(buffer, offset, count, cancellationToken);