C# - Error CS4033 - The 'await' operator can only be used within an async method

brother uyl 0 Reputation points
2023-11-06T07:14:04.71+00:00
Visual Studio Community 2022 failed to build the following code with C# - Error CS4033 - The 'await' operator can only be used within an async method.
Do you have any suggestion to fix this issue?

// in BluetoothDevicePairing\src\Bluetooth\Service\NusService.cs
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Storage.Streams;

namespace BluetoothDevicePairing.Bluetooth.Service;

public static class Nus {
    private static readonly Guid NordicUartServiceUuid          = Guid.Parse("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    private static readonly Guid NordicUartTxCharacteristicUuid = Guid.Parse("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    private static readonly Guid NordicUartRxCharacteristicUuid = Guid.Parse("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
 
    public static async Task<bool> SendMessage(string deviceId, string message) {
       ...
    }
}

// in BluetoothDevicePairing\src\Bluetooth\Devices\DevicePairer.cs
using System;
using System.Threading.Tasks;
using BluetoothDevicePairing.Bluetooth.Service;

namespace BluetoothDevicePairing.Bluetooth.Devices;

internal static class DevicePairer
{
    public static void PairDevice(Device device, string pinCode)
    {
       ....
        bool result = await Nus.SendMessage(device.GetId(), "test");
    }
}
Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Minxin Yu 13,506 Reputation points Microsoft External Staff
    2023-11-06T07:51:48.3466667+00:00

    Hi, @brother uyl

    The 'await' operator can only be used within an async method
    As the compiler error indicates, you need to make the method async

    public static async Task PairDevice(Device device, string pinCode)

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.