Visual C++ .NET/Development/IAsyncResult
Run Async Command against database
#include "stdafx.h"
using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
ref struct MyEventHandler{
static void CommandCompleted(IAsyncResult^ asyncResult){
SqlCommand^ asyncCommand = dynamic_cast<SqlCommand^>(asyncResult->AsyncState);
if ( asyncCommand!= nullptr )
SqlDataReader^ dataReader = asyncCommand->EndExecuteReader(asyncResult);
}
};
void main()
{
SqlConnectionStringBuilder^ connectionBuilder = gcnew SqlConnectionStringBuilder();
connectionBuilder->AsynchronousProcessing = true;
connectionBuilder->DataSource = "localhost";
connectionBuilder->InitialCatalog = "myCatalog";
connectionBuilder->UserID = "sa";
connectionBuilder->Password = "";
SqlConnection^ myConnection = gcnew SqlConnection(connectionBuilder->ToString());
myConnection->Open();
SqlCommand^ asyncCommand = myConnection->CreateCommand();
asyncCommand->CommandText = "SELECT * FROM Music";
AsyncCallback^ asyncCallback = gcnew AsyncCallback(MyEventHandler::CommandCompleted);
IAsyncResult^ asyncResult = asyncCommand->BeginExecuteReader(asyncCallback, asyncCommand);
asyncResult->AsyncWaitHandle->WaitOne();
}
Using IAsyncResult
#include "stdafx.h"
using namespace System;
using namespace System::Threading;
ref class MyClass{
public:
property String^ Value;
MyClass(String^ s) { Value = s; }
};
delegate void DoSearch(String^, MyClass^);
ref class Database{
IAsyncResult^ result;
MyClass^ m_r;
public:
Database(String^ s) { m_r = gcnew MyClass(s); }
void Query(String^ queryString, MyClass^ r){
r->Value = "New Value";
}
void InitiateQuery(String^ queryString){
DoSearch^ qf = gcnew DoSearch(this, &Database::Query);
Console::WriteLine(m_r->Value);
result = qf->BeginInvoke(queryString, m_r,gcnew AsyncCallback(this, &Database::ProcessResult),qf);
}
bool IsQueryCompleted(){
return result->IsCompleted;
}
void ProcessResult(IAsyncResult^ result)
{
DoSearch^ caller = (DoSearch^) result->AsyncState;
caller->EndInvoke(result);
Console::WriteLine(m_r->Value);
}
};
int main(){
Database doc("Old Value");
doc.InitiateQuery("SELECT * FROM Employee ");
while (! doc.IsQueryCompleted() ){
Thread::Sleep(100);
}
}