简体   繁体   中英

How to return a value into an asynchronous method?

When I call this method, nothing happens and the application crashes. I think it's due the ExecuteAsync method.can someone help me?.This is my code.

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;
    }   

I tried this code also but still the same problem exists.

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;
    }   

You don't want to use Task.Result or Task.Wait in asynchronous code. Those members are only used when you use Task as part of the Task Parallel Library (writing parallel code). They should almost never be used in asynchronous code.

In your case, I suspect that you're calling Result on the Task returned by Connect (or possibly further up the call stack). This can cause a deadlock , as I explain on my blog.

I disagree with @LasseVKarlsen regarding asynchronous code for beginners. I think it is absolutely something you should learn now that the new async / await language features are out.

I recommend you start with my introduction and follow up with the MSDN docs and the TAP pattern . Then review my best practices article to avoid the most common pitfalls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM