c# - 无法将类型 'System.Threading.Tasks.Task' 隐式转换为 'Windows.Foundation.IAsyncAction' 。存在显式转换

标签 c# multithreading azure asynchronous async-await

所以我用 C# 编写这个软件,但收到了此错误消息。对于我的一生,我无法弄清楚,无论我做什么,搜索都不会带来任何有用的东西。

代码本身:

private async Task LoginIoTHub()
{
    TypeJson command_json = new TypeJson();

    if (NowNetSta == false) return;
    if (IoTHubConnectFlag == false) return;

    if (TeamName == null)
    {
        Debug.WriteLine("Please don't let your team name be void when you call methods 'new IoTHubLocalService(xx,xx,xx)'");
        await Task.Delay(TimeSpan.FromSeconds(4));
    }
    else
    {
        if (LoginF == false)
        {
            try
            {
                Debug.WriteLine("Start to login\r\n");

                LoginJson login_msg = new LoginJson();
                login_msg.DeviceID = BoardID;
                login_msg.name = TeamName;

                var messageString = JsonConvert.SerializeObject(login_msg);

                command_json.Type = 1;
                command_json.Command = messageString;
                messageString = JsonConvert.SerializeObject(command_json);

                var message = new Message(Encoding.ASCII.GetBytes(messageString));
                IAsyncAction Action = deviceClient.SendEventAsync(message);

                await Action;

                if (Action.Status == AsyncStatus.Completed)
                {
                    Debug.WriteLine("Login success");
                    LoginF = true;
                }
                else
                {
                    Debug.WriteLine("Login failed");
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine("Login to IoT Hub failed, please check your team name and internet connection: " + ex.Message);
                await Task.Delay(TimeSpan.FromSeconds(10));
            }
        }
    }
}

最佳答案

DeviceClient.SendEventAsync(Message)返回 Task

Sends an event to device hub

public Task SendEventAsync(Message message)

将代码更改为

var Action = deviceClient.SendEventAsync(message);
await Action;

另请注意,Task 继承自 IAsyncResult,而不是像示例中那样继承自 IAsyncAction

您还可以使用 Task.IsCompleted Property 检查完成情况

if (Action.IsCompleted) { ...

关于c# - 无法将类型 'System.Threading.Tasks.Task' 隐式转换为 'Windows.Foundation.IAsyncAction' 。存在显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41618964/

相关文章:

c# - 如何获取要在DbContext c#中创建的下一个实体的主键(id)

c# - 如何使 Assert.AreEqual 通过 POCO

c# - 如果为空则返回零的 Lambda 表达式

wpf - 在 WPF 中取消 BeginInvoke

Azure Migrate : Tools to analyze the application and report - Technology stack, 版本,外部依赖项如数据库、kafka?

c# - 根据条件搜索数据

c++ - Boost 库中的信号和槽与多线程

c - Mutex - 使用线程计算文件中 char 的出现次数

azure - 数据源的列表和字符串转换问题

azure - 使用 Azure AD 的 OAuth2 - 未获得用户同意