views:

35

answers:

2

Hi, I am trying to understand what is IAsyncresult good and therefore I wrote this code. The problem is it behaves as I called "MetodaAsync" normal way. While debugging, the program stops here until the method completed. Any help appreciated, thank you.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        delegate int Delegat();

        static void Main(string[] args)
        {
            Program p=new Program();
            Delegat d = new Delegat(p.MetodaAsync);
            IAsyncResult a = d.BeginInvoke(null, null); //I have removed callback
            int returned=d.EndInvoke(a);
            Console.WriteLine("AAA");

        }
        private int MetodaAsync()
        {
            int AC=0;
            for (int I = 0; I < 600000; I++)
            {
                for (int A = 0; A < 6000000; A++)
                {

                }
                Console.Write("B");
            }
            return AC;
        }


    }
}
+1  A: 

It blocks in EndInvoke. You could do some useful work in the main thread between BeginInvoke and EndInvoke.

Henrik
So..if it is blocked, what is the asynchronicity here? Or when I do some stuff between Begin and EndIvoke it will be done simultaneously?
Petr
@Petr: yes, it will be executed concurrently.
Henrik
+2  A: 

In order to 'see' it is multithreaded, do something like:

IAsyncResult a = d.BeginInvoke(null, null); //I have removed callback
for (int j = 0; j < 100; j++)
{
    Console.Write("JJJ");
    Thread.Sleep(1);
}    
int returned=d.EndInvoke(a);
Console.WriteLine("AAA");

But in general, you would call EndInvoke from the callback.

Henk Holterman