2011-04-06 20 views

Respuesta

99

Si usa action.BeginInvoke(), tiene have to call EndInvoke en algún otro lugar; de lo contrario, el marco debe contener el resultado de la llamada asincrónica en el montón, lo que da como resultado una pérdida de memoria.

Si no desea pasar a C# 5 con las palabras clave async/await, puede usar la biblioteca Task Parallels en .Net 4. Es mucho, mucho mejor que usar BeginInvoke/EndInvoke, y proporciona una limpieza manera de disparar y olvidar para los trabajos asincrónicos:

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

Si tiene métodos para llamar a que tienen parámetros, se puede utilizar un lambda para simplificar la llamada sin tener que crear delegados:

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

Estoy bastante seguro (aunque no es positivo) de que la sintaxis asincrónica/esperar de C# 5 es jus t azúcar sintáctico alrededor de la biblioteca de tareas.

+2

Si aún no estaba claro, el supuesto final re: async/await es correcto, pero cambiará drásticamente la apariencia del código. – Gusdor

+0

Estoy intentando esto con un método que crea un evento y luego delega, ¿es correcto? Si es así, ¿cómo puedo finalizar la tarea? Cheers – Joster

24

Aquí hay una manera de hacerlo:

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


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

Por supuesto, es necesario sustituir Action por otro tipo de delegado si el método tiene una firma diferente

+1

cuando llamamos a foo entonces cómo puedo pasar argumento de que u no mostraron ? – Thomas

+0

@Thomas, no entiendo su pregunta ... –

+0

En lugar de null puede poner un objeto. Haga que Foo tome un parámetro de entrada de tipo objeto. A continuación, tendrá que convertir el objeto al tipo apropiado en Foo. –

4

Consulte el artículo de MSDN Asynchronous Programming with Async and Await si puedes permitirse jugar con cosas nuevas. Fue agregado a .NET 4.5. código

Ejemplo fragmento del enlace (que es en sí mismo de this MSDN sample code project):

// 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; 
} 

Citando:

Si AccessTheWebAsync no tiene ningún trabajo que se puede hacer entre la llamada y en espera de GetStringAsync Una vez completada, puede simplificar su código llamando y esperando en la siguiente declaración individual.

string urlContents = await client.GetStringAsync(); 

más detalles en la link.

1
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)); 
     } 
    } 
Cuestiones relacionadas