我是一名在异步操作方面不太专业的人,希望有人能帮我指出问题。
在我的其中一个方法中,我编写了一个包装器,
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;
}
在我的用户界面中,我这样调用方法:
int _recordsAffected = await MyClass.ExecuteNonQueryRawSQLAsync("INSERT....");
为了测试它是否真正起作用,我尝试在连接字符串中提供一个无效的数据库服务器地址,以便它不断搜索直到抛出异常。
当程序仍在连接时,UI会冻结。我的包装器缺少哪些东西?还是我需要做其他必要的初始化?
ExecuteNonQueryRawSQLAsync
方法的方式 - 是异步的吗? - Chris MantleExecuteNonQueryAsync()
。 - Rossana