YoZ
YoZ

Reputation: 23

Execute a synchronous command asynchronously in Xamarin

I've built a Xamarin.Forms app that is using a DLL from a tierce app to send kind of SQL command (this is not SQL !)

Probleme is that it only provides synchronous methods and my app is then "not responding". How can I do an asynchronous method that will call the sycnhronous one and wait for its result without hanging the UI ?

I tried the following but it seems to be waitng forever like if thread was never stopping.

public async Task<ExecuteCommandResult> ExecuteMocaCommandAsync(String ps_command)
    {
        return await Task<ExecuteCommandResult>.Run(() =>
            {
                return ExecuteMocaCommand(ps_command);
            }
        );
    }

and I'm calling it like this :

ExecuteCommandResult l_res = l_con.ExecuteMocaCommandAsync("list users where usr_id = '" + gs_UserName + "'").Result;

I'm clearly missing something and hope you can point me in the good direction.

Regards, Yoz

Upvotes: 0

Views: 174

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457302

The Task.Run looks good (though you can simplify it by changing Task<ExecuteCommandResult>.Run to just Task.Run). That's the proper way to push blocking work to a background thread in a UI application.

However, you can't use Result; that can deadlock. You'll need to call your method using await:

ExecuteCommandResult l_res = await l_con.ExecuteMocaCommandAsync("list users where usr_id = '" + gs_UserName + "'");

Upvotes: 1

Related Questions