等待操作符只能在异步方法中使用 [英] The await operator can only be used within an async method
本文介绍了等待操作符只能在异步方法中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的界面ISFactory
如下.
namespace MyApp.ViewModels
{
public interface IStreamFactory
{
Stream CreateSPStream(string sPName);
}
}
在Windows非通用版本中,上述功能的实现方式如下.
On Windows non-universal version the above function was implemented as follows.
public Stream CreateSerialPortStream(string serialPortName)
{
var p = new System.IO.Ports.SerialPort();
p.PortName = serialPortName;
p.BaudRate = 9600;
p.RtsEnable = true;
p.DtrEnable = true;
p.ReadTimeout = 150;
p.Open();
return p.BaseStream;
}
此实现在Windows Universal中不再可用.我的尝试如下所示.
This implementation is no longer available in Windows Universal. What I attempted is shown below.
public Stream CreateSerialPortStream(string serialPortName)
{
var selector = SerialDevice.GetDeviceSelector(serialPortName); //Get the serial port on port '3'
var devices = await DeviceInformation.FindAllAsync(selector);
if (devices.Any()) //if the device is found
{
var deviceInfo = devices.First();
var serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);
//Set up serial device according to device specifications:
//This might differ from device to device
serialDevice.BaudRate = 19600;
serialDevice.DataBits = 8;
serialDevice.Parity = SerialParity.None;
}
}
我收到以下错误消息.
await运算符只能在异步方法中使用.
The await operator can only be used within an async method.`
任何人都可以提出解决方法的建议.
Can anyone suggest a way around this.
推荐答案
最佳方法是使方法async
生效,因为编译器错误指示:
The best approach is to make the method async
, as the compiler error indicates:
public async Task<Stream> CreateSerialPortStreamAsync(string serialPortName)
这也需要更改界面:
Task<Stream> CreateSerialPortStreamAsync(string serialPortName);
是的,此方法的所有调用方都需要更新.
And yes, all callers of this method will need to be updated.
这篇关于等待操作符只能在异步方法中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文