Core/DBLayer: Implement async transaction completion callbacks

Port From (https://github.com/TrinityCore/TrinityCore/commit/0f0ca3a9194d76afa0227943e86469ad8368c5e2)
This commit is contained in:
hondacrx
2020-04-26 00:53:43 -04:00
parent a9d1d3f2b0
commit d450f6db3d
14 changed files with 224 additions and 109 deletions
@@ -17,6 +17,8 @@
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
namespace Framework.Database
{
@@ -52,10 +54,98 @@ namespace Framework.Database
}
public bool Execute<T>(MySqlBase<T> mySqlBase)
{
MySqlErrorCode errorCode = TryExecute(mySqlBase);
if (errorCode == MySqlErrorCode.None)
return true;
if (errorCode == MySqlErrorCode.LockDeadlock)
{
// Make sure only 1 async thread retries a transaction so they don't keep dead-locking each other
lock (_deadlockLock)
{
byte loopBreaker = 5; // Handle MySQL Errno 1213 without extending deadlock to the core itself
for (byte i = 0; i < loopBreaker; ++i)
if (TryExecute(mySqlBase) == MySqlErrorCode.None)
return true;
}
}
return false;
}
public MySqlErrorCode TryExecute<T>(MySqlBase<T> mySqlBase)
{
return mySqlBase.DirectCommitTransaction(m_trans);
}
SQLTransaction m_trans;
public static object _deadlockLock = new object();
}
class TransactionWithResultTask : TransactionTask
{
public TransactionWithResultTask(SQLTransaction trans) : base(trans) { }
public new bool Execute<T>(MySqlBase<T> mySqlBase)
{
MySqlErrorCode errorCode = TryExecute(mySqlBase);
if (errorCode == MySqlErrorCode.None)
{
m_result.SetResult(true);
return true;
}
if (errorCode == MySqlErrorCode.LockDeadlock)
{
// Make sure only 1 async thread retries a transaction so they don't keep dead-locking each other
lock (_deadlockLock)
{
byte loopBreaker = 5; // Handle MySQL Errno 1213 without extending deadlock to the core itself
for (byte i = 0; i < loopBreaker; ++i)
{
if (TryExecute(mySqlBase) == MySqlErrorCode.None)
{
m_result.SetResult(true);
return true;
}
}
}
}
m_result.SetResult(false);
return false;
}
public Task<bool> GetFuture() { return m_result.Task; }
TaskCompletionSource<bool> m_result = new TaskCompletionSource<bool>();
}
public class TransactionCallback : ISqlCallback
{
public TransactionCallback(Task<bool> future)
{
m_future = future;
}
public void AfterComplete(Action<bool> callback)
{
m_callback = callback;
}
public bool InvokeIfReady()
{
if (m_future != null && m_future.Wait(0))
{
m_callback(m_future.Result);
return true;
}
return false;
}
Task<bool> m_future;
Action<bool> m_callback;
}
}