The await operator can only be used within an async method

后端 未结 2 442
生来不讨喜
生来不讨喜 2021-01-29 14:24

I have an interface ISFactory as follows.

namespace MyApp.ViewModels
{
    public interface IStreamFactory
    {
        Stream CreateSPStream(strin         


        
相关标签:
2条回答
  • 2021-01-29 15:07

    The best approach is to make the method async, as the compiler error indicates:

    public async Task<Stream> CreateSerialPortStreamAsync(string serialPortName)
    

    This will require the interface to change as well:

    Task<Stream> CreateSerialPortStreamAsync(string serialPortName);
    

    And yes, all callers of this method will need to be updated.

    0 讨论(0)
  • 2021-01-29 15:08

    1) (Preferable) You can make your method async by changing its sugnature to :

    public  async Task<Stream> CreateSerialPortStream(string serialPortName)
    

    each method calling CreateSerialPortStream should be async too. (Also i suggest to rename your method to CreateSerialPortStreamAsync)

    2) If you don't want to change your method signature for some reason, you can leave it as is, but use Wait(). In this case, you will lose asynchronous calling.

    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;
          }
    }
    
    0 讨论(0)
提交回复
热议问题