gpt4 book ai didi

c# - MySQL 异步 - 我如何使用它?

转载 作者:行者123 更新时间:2023-11-29 19:08:23 24 4
gpt4 key购买 nike

我尝试运行我自己的 TCP 应用程序,现在我将检查用户是否退出。

我的问题是:如何使用 mySQL Async?

        public static bool CheckUserLogin(string Username,string Password){
try{
if(string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)){ return false; }
if (!System.Text.RegularExpressions.Regex.IsMatch(Username, "^[a-zA-Z0-9\x20]+$")) { return false; }
if (!System.Text.RegularExpressions.Regex.IsMatch(Password, "^[a-zA-Z0-9\x20]+$")) { return false; }
bool UserExit = false;
DataBase_Connection.DB_Conn.OpenAsync();
try{
string c_query = "SELECT COUNT(*) FROM `KoN_Account` WHERE BINARY `AccountName` = @U_Name AND `HashPass` = @P_Pass LIMIT 1;";
using (MySqlCommand CU_cmd = new MySqlCommand(c_query, db_Conn)){
CU_cmd.Parameters.AddWithValue("@U_Name", Username);
CU_cmd.Parameters.AddWithValue("@P_Pass", Password);
var count = CU_cmd.ExecuteScalar();
UserExit = Convert.ToBoolean(count);
}
}
catch{
}
DataBase_Connection.DB_Conn.CloseAsync();
return UserExit;
}
catch (Exception ex){
LoginConsole.WriteConsoleLoginParams(System.ConsoleColor.Red, "ERROR CheckUserLogin", ex.ToString() + "\nFailed to connect to the database (server shutdown...)");
}
return false;
}

我的问题是我做的对吗?使用OpenAsyncCloseAsync

另外我如何使用:以异步方式执行Scalar?

感谢您的帮助

最佳答案

为了使用async版本,您将需要更改返回 bool 的方法返回 Task<bool>并添加 async修饰符,那么您将需要使用 Async后缀方法和 await他们。

我也会做DB_Conn.CloseAsync()finally block ,并删除空捕获,因为您已经有了某种形式的基本错误处理。

请注意,您只能使用 awaitcatchfinally使用 C#6 及更高版本时。

所以你的例子看起来像:

public static async Task<bool> CheckUserLogin(string Username, string Password)
{
try
{
if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) { return false; }
if (!System.Text.RegularExpressions.Regex.IsMatch(Username, "^[a-zA-Z0-9\x20]+$")) { return false; }
if (!System.Text.RegularExpressions.Regex.IsMatch(Password, "^[a-zA-Z0-9\x20]+$")) { return false; }
bool UserExit = false;
await DataBase_Connection.DB_Conn.OpenAsync();
try
{
string c_query = "SELECT COUNT(*) FROM `KoN_Account` WHERE BINARY `AccountName` = @U_Name AND `HashPass` = @P_Pass LIMIT 1;";
using (MySqlCommand CU_cmd = new MySqlCommand(c_query, db_Conn))
{
CU_cmd.Parameters.AddWithValue("@U_Name", Username);
CU_cmd.Parameters.AddWithValue("@P_Pass", Password);
var count = await CU_cmd.ExecuteScalarAsync();
UserExit = Convert.ToBoolean(count);
}
}
finally
{
await DataBase_Connection.DB_Conn.CloseAsync();
}
return UserExit;
}
catch (Exception ex)
{
LoginConsole.WriteConsoleLoginParams(System.ConsoleColor.Red, "ERROR CheckUserLogin", ex.ToString() + "\nFailed to connect to the database (server shutdown...)");
}
return false;
}

关于c# - MySQL 异步 - 我如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43306496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com