web-dev-qa-db-fra.com

Comment appeler une méthode de manière asynchrone en c #

Quelqu'un pourrait-il me montrer un petit extrait de code qui montre comment appeler une méthode de manière asynchrone en c #?

98
Thomas

Si vous utilisez action.BeginInvoke (), vous devez appeler EndInvoke quelque part - sinon, la structure doit conserver le résultat de l'appel asynchrone sur le tas, ce qui entraîne une fuite de mémoire.

Si vous ne voulez pas passer au C # 5 avec les mots-clés async/wait, vous pouvez simplement utiliser la bibliothèque Task Parallels dans .Net 4. C'est beaucoup, beaucoup plus agréable que d'utiliser BeginInvoke/EndInvoke, et vous permet de and-oublier pour les travaux asynchrones:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();

Si vous avez des méthodes à appeler qui prennent des paramètres, vous pouvez utiliser un lambda pour simplifier l'appel sans avoir à créer de délégués:

void Foo2(int x, string y)
{
    return;
}
...
new Task(() => { Foo2(42, "life, the universe, and everything");}).Start();

Je suis à peu près sûr (mais certes pas positif) que la syntaxe C/5 async/wait est juste un sucre syntaxique autour de la bibliothèque de tâches.

122
Drew Shafer

À partir de .Net 4.5, vous pouvez utiliser Task.Run pour lancer simplement une action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx

46
ms007

Voici un moyen de le faire:

// The method to call
void Foo()
{
}


Action action = Foo;
action.BeginInvoke(ar => action.EndInvoke(ar), null);

Bien sûr, vous devez remplacer Action par un autre type de délégué si la méthode a une signature différente

24
Thomas Levesque

Consultez l'article MSDN Programmation asynchrone avec Async et Await si vous pouvez vous permettre de jouer avec de nouvelles choses. Il a été ajouté à .NET 4.5.

Exemple de code extrait du lien (qui provient lui-même de ce projet de code exemple MSDN ):

// Three things to note in the signature: 
//  - The method has an async modifier.  
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer. 
//  - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.Microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}

Citant:

Si AccessTheWebAsync n'a aucun travail à effectuer entre appeler GetStringAsync et attendre son achèvement, vous pouvez simplifier votre code en appelant et en attente dans la seule instruction suivante.

string urlContents = await client.GetStringAsync();

Plus de détails sont dans le lien .

4
Michael Blake
public partial class MainForm : Form
{
    Image img;
    private void button1_Click(object sender, EventArgs e)
    {
        LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
    }

    private void LoadImageAsynchronously(string url)
    {
        /*
        This is a classic example of how make a synchronous code snippet work asynchronously.
        A class implements a method synchronously like the WebClient's DownloadData(…) function for example
            (1) First wrap the method call in an Anonymous delegate.
            (2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
            (3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
            (4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
        */
        try
        {
            Func<Image> load_image_Async = delegate()
            {
                WebClient wc = new WebClient();
                Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
                wc.Dispose();
                return bmpLocal;
            };

            Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
            {
                Func<Image> ss = (Func<Image>)ar.AsyncState;
                Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);

                if (img != null) img.Dispose();
                if (myBmp != null)
                    img = myBmp;
                Invalidate();
                //timer.Enabled = true;
            };
            //load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);             
            load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);             
        }
        catch (Exception ex)
        {

        }
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        if (img != null)
        {
            Graphics grfx = e.Graphics;
            grfx.DrawImage(img,new Point(0,0));
        }
    }
1
Dr.Sai