using System; using System.Collections.Generic; using System.Threading.Tasks; using Dapper; using MySql.Data.MySqlClient; namespace Hncore.Infrastructure.Common { public class ConcurrentHelper { private static string _connString = ""; private static string _tableName = "concurrent_helper"; private List _infos = new List(); private string _id; public static void Init(string mysqlConn) { _connString = mysqlConn; MySqlHelper.Execute(_connString , $@"create table if not exists {_tableName} ( Id VARCHAR(32) PRIMARY KEY UNIQUE, CreateTime datetime DEFAULT now(), Info text )" ); } public ConcurrentHelper AddInfo(string info) { _infos.Add(info); return this; } private async Task GetAuthority() { try { string info = ListHelper.ListToStr(_infos, "\n"); _id = SecurityHelper.GetMd5Hash(info); string sql = $"insert into {_tableName}(Id,Info) values(@Id,@Info)"; await MySqlHelper.ExecuteAsync(_connString, sql, new {Id = _id, Info = info}); } catch { return false; } return true; } public async Task Execute(Action action) { try { if (await GetAuthority()) { action(); } } catch (Exception e) { await MySqlHelper.ExecuteAsync(_connString, $"DELETE FROM {_tableName} where Id='{_id}'"); throw e; } } } }