我有一个接口ISFactory
,如下所示。
namespace MyApp.ViewModels
{
public interface IStreamFactory
{
Stream CreateSPStream(string sPName);
}
}
在Windows非通用版本上,上述功能实现如下。
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中不再提供此实现。我尝试的内容如下所示。
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运算符只能在异步方法中使用。
任何人都可以建议解决这个问题。
答案 0 :(得分:9)
最佳方法是制作方法async
,因为编译器错误指示:
public async Task<Stream> CreateSerialPortStreamAsync(string serialPortName)
这将要求界面也改变:
Task<Stream> CreateSerialPortStreamAsync(string serialPortName);
是的,此方法的所有调用者都需要更新。
答案 1 :(得分:0)
1)(首选)您可以通过将其sugnature更改为:
来使您的方法 asyncpublic async Task<Stream> CreateSerialPortStream(string serialPortName)
调用CreateSerialPortStream
的每个方法也应该是异步的。 (另外我建议将你的方法重命名为 CreateSerialPortStreamAsync )
2)如果由于某种原因您不想更改方法签名,可以保留原样,但使用 Wait()。在这种情况下,您将失去异步调用。
public Stream CreateSerialPortStream(string serialPortName)
{
var selector = SerialDevice.GetDeviceSelector(serialPortName); //Get the serial port on port '3'
var devicesTask = await DeviceInformation.FindAllAsync(selector);
devicesTask.Wait();
var devices = devicesTask.Result;
if (devices.Any()) //if the device is found
{
var deviceInfo = devices.First();
var serialDeviceTask = SerialDevice.FromIdAsync(deviceInfo.Id);
serialDeviceTask.Wait();
var serialDevice = serialDeviceTask.Result;
//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;
}
}