Note: les exemples sont développés avec Snippet Compiler.
L'implementation d "Asynchronous Delegate" a le mérite de facilité le passage de paramètres, d'autoriser le retour de plusieurs valeurs (via ref/out) et de capturer les exceptions.
Exemple 1:
Assez rudimentaire il présente l'utilisation d'un asynchronous delegateFichier: Threading_AsynchronousDelegate.cs
using System;
using System.Collections.Generic;
using System.Threading;
public class MyClass
{
public delegate void DoWork ( out string workerMessage );
public static void RunSnippet()
{
// Take the Delegate
// Instanciate the Delegate with to a correct method signature
DoWork FillTheBottle = DoWork_FillTheBottle;
// NB:
// If DoWork_FillTheBottle was not Static we would use...
// DoWork FillTheBottle = (DoWork)(new MyClass().DoWork_FillTheBottle);
// Fire Async call
// parameters are deletage signature parameters + Callback + Data objet
String sMessage = String.Empty;
IAsyncResult cookieFillTheBottle = FillTheBottle.BeginInvoke( out sMessage, null, null );
// Join the Async call
FillTheBottle.EndInvoke( out sMessage, cookieFillTheBottle );
WL( "Fill the Bottle returned: "+sMessage );
}
public static void DoWork_FillTheBottle(out string sMessage){
for( int i=0; i<3; i++ ){
WL( " GlouGlou... filling the bottle" );
Thread.Sleep( TimeSpan.FromSeconds(1) );
}
sMessage= "Voila, I filled the bottle";
}
...
}
Exemple 2:
Cet exemple un peu plus détaillé montre l'utilisation de plusieurs workers, avec des signatures différentes et la capture des exceptions. Fichier: Threading_AsynchronousDelegate2.cs
Aucun commentaire:
Enregistrer un commentaire