Rossana
Rossana

Reputation: 187

UI still freezing when using async/await

I'm no expert in terms of asychronous operations and hoping that someone can help me point out the problem.

In one of my methods I have written a wrapper,

public static async Task<int> ExecuteNonQueryRawSQLAsync(string sqlStatement)
{
    int _returnValue = -1;
    using (SqlConnection _conn = new SqlConnection("connectionString"))
    {
        using (SqlCommand _comm = new SqlCommand())
        {
            _comm.Connection = _conn;
            _comm.CommandText = sqlStatement;
            _comm.CommandType = CommandType.Text;

            // other codes on setting parameter

            try
            {
                await _conn.OpenAsync();
                _returnValue = Convert.ToInt32(await _comm.ExecuteNonQueryAsync());
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
    return _returnValue;
}

in my UI, I call the method like this,

int _recordsAffected = await MyClass.ExecuteNonQueryRawSQLAsync("INSERT....");

To test if it's really working, i tried to supply an invalid database server address in the connection string so it keeps on searching until it throws an exception.

While the program is still connecting, the UI freezes. What are the things that are missing in my wrapper? or are there any other needed initializations that I need to do?

Upvotes: 3

Views: 1270

Answers (2)

Tormod
Tormod

Reputation: 4573

await "somemethod" doesn't mean that the method is called asynchronosly. You are still doing a regular method call that will run like any other until the method being called decides to return a task representing an asynchronous operation, which you then await.

If the method does a bunch of time consuming stuff before returning the awaitable task, you can call it using TaskFactory.Startnew().

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062502

From bitter memory, TCP sockets have a very similar issue - basically, the name resolution is performed synchronously, even for the async operations. There are two ways around this:

  • use an IP address instead of a name
  • make sure you start the Open* / Connect* / whatever from a worker thread - perhaps Task.StartNew

Untested, but presumably:

await Task.StartNew(_conn.Open);

Upvotes: 5

Related Questions