小编Ros*_*ana的帖子

使用async/await时UI仍然冻结

我不是在同步操作方面的专家,并希望有人可以帮助我指出问题所在.

在我的一个方法中,我写了一个包装器,

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;
}
Run Code Online (Sandbox Code Playgroud)

在我的UI中,我调用这样的方法,

int _recordsAffected = await MyClass.ExecuteNonQueryRawSQLAsync("INSERT....");
Run Code Online (Sandbox Code Playgroud)

为了测试它是否真的有效,我试图在连接字符串中提供一个无效的数据库服务器地址,以便它继续搜索,直到它抛出异常.

当程序仍然连接时,UI冻结.我的包装中缺少什么东西?或者我需要进行其他任何需要的初始化吗?

c# asynchronous winforms

3
推荐指数
1
解决办法
1072
查看次数

标签 统计

asynchronous ×1

c# ×1

winforms ×1