概要
我目前正在尝试使用MySQL数据库库执行select语句,并以回调的方式将其返回给匿名语句lambda。这就是这个特定的库(大多数是未记录的)如何处理请求。我还需要等待此过程完成。
我当前正在尝试使用一种async
方法,但是似乎断言任务的完成为时过早(即await taskName;
在回调完成之前就被绕过了,因此返回的字典为空)。
我尝试使用完成标志方法,其中布尔标志用于表示回调是否已完成,并Task.Yield()
在返回任务之前在while循环中使用。
下面是来自两个不同类的两个函数。第一个来自数据库类,第二个来自实用程序类(从中调用数据库类)。
码
/// <summary>
/// Asynchronously executes a select MySQL statement and returns a dictionary of rows selected.
/// </summary>
/// <param name="statement"></param>
/// <returns></returns>
public async Task<Dictionary<int, object>> ExecuteSelectAsync (string statement)
{
// Init dictionary of rows and counter for each row
Dictionary<int, object> responseData = new Dictionary<int, object>();
int i = 0;
bool complete = false;
DatabaseLibrary.execute(
statement,
new Action<dynamic> (s =>
{
// Take the data returned as 's' and populate the 'responseData' dictionary.
Utility.LogDebug("Database", "Executed select statement with " + numberOfRows.ToString() + " rows");
})
);
Utility.LogDebug("Database", "Returning select execution response"); // By this point, the lambda expression hasn't been executed.
return responseData; // This is empty at time of return.
}
/// <summary>
/// Checks the supplied data against the database to validate.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static async Task<bool> ValidateData(string data)
{
Database database = new Database();
Task<Dictionary<int, object>> selectTask = database.ExecuteSelectAsync("SELECT fieldname FROM tablename WHERE data='" + data + "'"); // Excuse statement forming, this is just to test
await selectTask;
try
{
Dictionary<string, object> firstRow = (Dictionary<string, object>)selectTask.Result[0];
if ((int)firstRow["fieldname"] == 0) return false; // data not valid, return false
else return true; // data valid, return true
}
catch (Exception e)
{
LogException("Utility", e);
LogDebug("Utility", "Database class returned empty result set");
return false; // Empty result, presume false
}
}
我知道这段代码可以正常工作,因为在显示Returning select execution response
控制台输出后不久,就会输出第二行读数Executed select statement with x rows
。这里的主要问题是存在竞争条件。如何确保在处理数据之前正确填充了数据?
您将需要一种方法使数据库回调向您的代码发出已被调用并且可以恢复执行的信号。最简单的方法就是使用TaskCompletionSource
。它看起来像:
public async Task<Dictionary<int, object>> ExecuteSelectAsync (string statement)
{
// declare the TaskCompletionSource that will hold the database results
var tcs = new TaskCompletionSource<Dictionary<int, object>>();
DatabaseLibrary.execute(
statement,
new Action<dynamic> (s =>
{
// Take the data returned as 's' and populate the 'responseData' dictionary.
Utility.LogDebug("Database", "Executed select statement with " + numberOfRows.ToString() + " rows");
var data = new Dictionary<int, object>();
// build your dictionary here
// the work is now complete; set the data on the TaskCompletionSource
tcs.SetResult(data);
})
);
// wait for the response data to be created
var responseData = await tcs.Task;
Utility.LogDebug("Database", "Returning select execution response");
return responseData;
// if you don't need the logging, you could delete the three lines above and
// just 'return tcs.Task;' (or move the logging into the callback)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句