user2169047
user2169047

Reputation: 77

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

Upvotes: 2

Views: 2050

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457472

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.

Upvotes: 2

Related Questions