I am providing code of asynchronous database query with explanation so that you can understand it properly.
Code:
delegate string getResult (int i);
static void compareResult ()
{
// Declaration and instantiation of the two delegates
// With the getResult-Signature:
Result1 = new DBRetriever getResult (), getResult,.
Result2 = new DBRetriever getResult (), getResult,.
// Start the retrieval from the database:
IAsyncResult cookie1 result1.BeginInvoke = (1, null, null);
IAsyncResult cookie2 result2.BeginInvoke = (2, null, null);
// Perform some random calculation:
double seed = 1.23;
for (int i = 0; i <1000000; i + +)
seed = Math.sqrt (seed + 1000);
// Get the results, waiting for completion if necessary.
// Here's where any exceptions thrown will be:
string s1 = result1.EndInvoke (cookie1);
string s2 = result2.EndInvoke (cookie2);
Console.WriteLine (? S1 == s2 "Same" "Different");
}
The example starts with the declaration and instantiation of the two delegates, the referenced methods will be executed asynchronously. Each of these two delegate referring to a DBRetriever object. In the example we also assume that DBRetriever does not allow concurrent access. If that were not enough, a single delegate. Then be by BeginInvoke methods activated and then branches back to the caller immediately. As a function parameter, and in consultation with the delegate of an integer date is required. Furthermore, two parameters, an optional callback and a data object must be passed. In this example, however, are not used and therefore replaced by zero. BeginInvoke returns an object of type IASynchResult back. This serves as a cookie for calling EndInvoke below. IASynchResult also has the attribute IsCompleted to monitor the process progress and its Beendigung.Nach the call to BeginInvoke can continue to work with other routine. In the example here, made some mathematical calculations. Calling EndInvoke delivers the results back, in the example strings. Threads should not be terminated worker called the waiting EndInvoke at this point. If during the execution of the asynchronous method, an exception occurs, it will be further channeled to the caller.
Bookmarks