SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
conn.Open();
SACommand cmd = new SACommand(
"UPDATE Departments"
+ " SET DepartmentName = 'Engineering'"
+ " WHERE DepartmentID=100",
conn );
IAsyncResult res = cmd.BeginExecuteNonQuery();
// perform other work
// this will block until the command completes
int rowCount reader = cmd.EndExecuteNonQuery( res );
(2) 轮询 IAsyncResult 的 IsCompleted 属性。
可以轮询 IAsyncResult 的 IsCompleted 属性。例如:
SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
conn.Open();
SACommand cmd = new SACommand(
"UPDATE Departments"
+ " SET DepartmentName = 'Engineering'"
+ " WHERE DepartmentID=100",
conn );
IAsyncResult res = cmd.BeginExecuteNonQuery();
while( !res.IsCompleted ) {
// do other work
}
// this will not block because the command is finished
int rowCount = cmd.EndExecuteNonQuery( res );
SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
conn.Open();
SACommand cmd = new SACommand(
"UPDATE Departments"
+ " SET DepartmentName = 'Engineering'"
+ " WHERE DepartmentID=100",
conn );
IAsyncResult res = cmd.BeginExecuteNonQuery();
// perform other work
WaitHandle wh = res.AsyncWaitHandle;
wh.WaitOne();
// this will not block because the command is finished
int rowCount = cmd.EndExecuteNonQuery( res );
(4) 调用 BeginExecuteNonQuery 时指定回调函数。
可在调用 BeginExecuteNonQuery 时指定回调函数。例如:
private void callbackFunction( IAsyncResult ar ) {
SACommand cmd = (SACommand) ar.AsyncState;
// this won't block since the command has completed
int rowCount = cmd.EndExecuteNonQuery();
}
// elsewhere in the code
private void DoStuff() {
SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
conn.Open();
SACommand cmd = new SACommand(
"UPDATE Departments"
+ " SET DepartmentName = 'Engineering'"
+ " WHERE DepartmentID=100",
conn );
IAsyncResult res = cmd.BeginExecuteNonQuery( callbackFunction, cmd );
// perform other work. The callback function will be
// called when the command completes
}