如何将值返回到异步方法

本文关键字:异步方法 返回 | 更新日期: 2023-09-27 18:04:06

当我调用这个方法时,什么都没有发生,应用程序崩溃了。我认为这是由于ExecuteAsync方法。有人能帮帮我吗?这是我的代码。

CODE1 :

public Task<Connection> Connect(string userId, string password)
    {
        var client = new RestClient(_baseUrl)
            {
                Authenticator = new SimpleAuthenticator("user", userId,
                     "password", password)
            };
        var tcs = new TaskCompletionSource<Connection>();
        var request = new RestRequest(AppResources.Authenticating);
        client.ExecuteAsync<Connection>(request, response => tcs.SetResult(new 
               JsonDeserializer().Deserialize<Connection>(response)));
        return tcs.Task;
    }   

我也试过这个代码,但仍然存在同样的问题。

CODE2 :

public async Task<Connection> Connect(string userId, string password)
    {
        var client = new RestClient(_baseUrl)
            {
                Authenticator = new SimpleAuthenticator("user", userId,
                      "password", password)
            };
        var tcs = new TaskCompletionSource<Connection>();
        var request = new RestRequest(AppResources.Authenticating);
        client.ExecuteAsync<Connection>(request, response => tcs.SetResult(new 
                JsonDeserializer().Deserialize<Connection>(response)));
        Debug.WriteLine(tcs.Task.Result.Data);
        return await tcs.Task;
    }   

如何将值返回到异步方法

不要在异步代码中使用Task.ResultTask.Wait。只有当您使用Task作为任务并行库的一部分(编写并行代码)时才使用这些成员。它们几乎不应该在异步代码中使用。

在你的情况下,我怀疑你在Connect返回的Task上调用Result(或者可能在调用堆栈上进一步)。这可能会导致死锁,正如我在博客中解释的那样。

我不同意@LasseVKarlsen关于初学者异步代码的观点。我认为这绝对是你现在应该学习的东西,因为新的async/await语言特性已经出来了。

我建议你从我的介绍开始,接着看MSDN文档和TAP模式。然后查看我的最佳实践文章,以避免最常见的陷阱。