Why my async call does not work?
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;
}
}
}
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.
It blocks in EndInvoke. You could do some useful work in the main thread between BeginInvoke and EndInvoke.
精彩评论