/// <summary> /// 开始执行数据库写入循环任务 /// </summary> public void StartWork() { _loopToken = new CancellationTokenSource(); Thread thread = new Thread(() => { while (!_loopToken.IsCancellationRequested) { try { bool has = false; do { has = Execute(); } while (has); Thread.Sleep(1); } catch (Exception ex) { UnHandledSqlCommandExecuteException?.Invoke(this, ex); } } }); thread.Start(); }
private bool Execute() { int lines = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < MaxLines; i++) { if (SmartDbBus.SqlQueue.TryDequeue(out var sql)) { sb.Append(sql.EndsWith(";") ? sql : sql + ";"); lines++; } else { break; } } //执行操作 if (lines > 0) { _watch.Reset(); _watch.Start(); IDbTransaction trx = null; bool isopend = _connWriter.State == ConnectionState.Open; int retrytimes = 0;//重试十次 do { try { if (!isopend) { _connWriter.Open(); //数据库连接打开 } trx = _connWriter.BeginTransaction(); isopend = true; } catch (MySqlException ex) { if (_connWriter != null) { _connWriter.Dispose();//数据库连接关闭 if (trx != null) { trx.Dispose(); } } //if (ex.Message.Contains("Fatal error encountered during command execution.")) //{ //} _connWriter = new MySqlConnection(_connstr); retrytimes++; Thread.Sleep(500 * retrytimes); } } while (!isopend && retrytimes <= 10); if (trx == null) { var ex = new SmartDbExecuteException(sb.ToString(), "Can't create db transaction"); UnHandledSqlCommandExecuteException(this, ex); throw ex; } string sql = sb.ToString(); try { var cmd = _connWriter.CreateCommand(); cmd.Transaction = trx; cmd.CommandText = sql; SqlCommandExecuting?.Invoke(sql); cmd.ExecuteNonQuery(); trx.Commit(); } catch (Exception ex) { trx.Rollback(); UnHandledSqlCommandExecuteException?.Invoke(this, new Exception($"{ex.Message}\n{sql}", ex)); } finally { trx.Dispose(); } _watch.Stop(); this.OnProcessing(lines, _watch.ElapsedMilliseconds); return(true); } return(false); }