![](/img/trans.png)
[英]Exception thrown when opening a Excel spreedsheet from C# stating file is being used by another user
[英]No exception being thrown when opening MySqlConnection?
我剛開始使用異步和任務,我的代碼已經停止處理。 當我有一個傳入的網絡數據包並且我嘗試與數據包處理程序內的數據庫進行通信時,就會發生這種情況。
public class ClientConnectedPacket : IClientPacket
{
private readonly EntityFactory _entityFactory;
public ClientConnectedPacket(EntityFactory entityFactory)
{
_entityFactory= entityFactory;
}
public async Task Handle(NetworkClient client, ClientPacketReader reader)
{
client.Entity = await _entityFactory.CreateInstanceAsync( reader.GetValueByKey("unique_device_id"));
// this Console.WriteLine never gets reached
Console.WriteLine($"Client [{reader.GetValueByKey("unique_device_id")}] has connected");
}
}
從異步任務調用 Handle 方法
if (_packetRepository.TryGetPacketByName(packetName, out var packet))
{
await packet.Handle(this, new ClientPacketReader(packetName, packetData));
}
else
{
Console.WriteLine("Unknown packet: " + packetName);
}
這是我認為導致問題的方法
public async Task<Entity> CreateInstanceAsync(string uniqueId)
{
await using (var dbConnection = _databaseProvider.GetConnection())
{
dbConnection.SetQuery("SELECT COUNT(NULL) FROM `entities` WHERE `unique_id` = @uniqueId");
dbConnection.AddParameter("uniqueId", uniqueId);
var row = await dbConnection.ExecuteRowAsync();
if (row != null)
{
return new Entity(uniqueId, false);
}
}
return new Entity(uniqueId,true);
}
DatabaseProvider 的 GetConnection 方法:
public DatabaseConnection GetConnection()
{
var connection = new MySqlConnection(_connectionString);
var command = connection.CreateCommand();
return new DatabaseConnection(_logFactory.GetLogger(), connection, command);
}
DatabaseConnection 的構造函數:
public DatabaseConnection(ILogger logger, MySqlConnection connection, MySqlCommand command)
{
_logger = logger;
_connection = connection;
_command = command;
_connection.Open();
}
當我注釋掉這一行時,它到達了Console.WriteLine
_connection.Open();
我在 .NET Core 3.1 控制台應用程序上運行了一個 POC 項目,使用 MySql.Data 8.0.19 和 MySqlConnector 0.63.2 旋轉 100 個並行任務。 我在每個任務的上下文中創建、打開和處理連接。 兩個提供程序都運行完成而沒有錯誤。
具體情況是 MySql.Data 查詢同步運行,盡管該庫提供異步方法簽名,例如 ExecuteReaderAsync() 或 ExecuteScalarAsync(),而 MySqlConnector 真正異步運行。
你可能會遇到:
MySQL 的多線程必須使用獨立連接。 鑒於此,多線程不是 MySQL 問題,而是客戶端語言的問題,C# 在您的問題中。
也就是說,在不考慮 MySQL 的情況下構建您的線程,然后在每個需要執行查詢的線程中創建一個連接。 如果您需要在線程之間傳遞數據,它將落在您的肩上。
我通常發現優化查詢消除了我的應用程序多線程的誘惑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.