await运算符只能在异步方法中使用

liv*_*hak -3 c# async-await

我有一个ISFactory如下界面.

namespace MyApp.ViewModels
{
    public interface IStreamFactory
    {
        Stream CreateSPStream(string sPName);
    }
}
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误.

await运算符只能在异步方法中使用

任何人都可以建议解决这个问题.

Ste*_*ary 10

最好的办法是使该方法async,因为编译器错误指示:

public async Task<Stream> CreateSerialPortStreamAsync(string serialPortName)
Run Code Online (Sandbox Code Playgroud)

这将要求界面也改变:

Task<Stream> CreateSerialPortStreamAsync(string serialPortName);
Run Code Online (Sandbox Code Playgroud)

是的,此方法的所有调用者都需要更新.