问题描述
我渴望加入超时功能,以我的 stream.ReadAsync()
并阅读微软在这篇文章中帮助的之间的桥接。本文建议使用 AsTask()
来实现这一目标。但是我的C#似乎并没有认识到 AsTask()
的。
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.
我使用的的Visual Studio 2013 是 Windows 7中与使用的System.Threading;
,这是一张code,我有:
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 :)
更新:这是安装.NET软件包列表,我想说的Visual Studio 2013采用4.5
UPDATE: These are the list of .NET packages installed and I would say Visual Studio 2013 uses 4.5
推荐答案
由于@Noseratio评论说,在 AsTask
中的链接文章是WinRT的异步操作,没有首创置业类型
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);
这篇关于AsTask不存在实行取消超时异步读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!