非同期プロセスがファイルの内容を読み込む


class Class1
{
public delegate int AsyncEventHandler(int a);
static List<string> l = new List<string>();
static int ps = 1000;
static long end = 0;
static long start = 0;

void Event1()
{
Console.WriteLine("Event1 Start");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Event1 End");
}

int Event2(int pi)
{
Console.WriteLine("Event2 Start " + pi + " ");

for (int i = 0; i < ps; i++)
{
Console.WriteLine(l[(pi - 1) * ps + i]);
}
Console.WriteLine("Event2 End " + pi + " ");
return pi;
}

void CallbackMethod(IAsyncResult ar)
{
var del = (AsyncEventHandler)ar.AsyncState;
var a = del.EndInvoke(ar);
Console.WriteLine(" " + a + " ------------------ :" + (end - start).ToString() + "-------------------------");
//((AsyncEventHandler)ar.AsyncState).EndInvoke(ar);
}


[STAThread]
static void Main(string[] args)
{
Class1 c = new Class1();
Console.WriteLine("ready");
start = DateTime.Now.Ticks;

//AsyncEventHandler asy = new AsyncEventHandler(c.Event1);
//IAsyncResult ia = asy.BeginInvoke(new AsyncCallback(c.CallbackMethod), asy);
//c.Event2();
//asy.EndInvoke(ia);



using (StreamReader sr = new StreamReader(@"R:\123.txt", Encoding.Default))
{
AsyncEventHandler asy = new AsyncEventHandler(c.Event2);
var line = sr.ReadLine();
while (line != null)
{
l.Add(line);
if (l.Count % ps == 0 && l.Count > 0)
{
IAsyncResult ia = asy.BeginInvoke(l.Count / ps, new AsyncCallback(c.CallbackMethod), asy);
}
//Console.WriteLine(line);//=144218750
//Task<int>.Factory.FromAsync(asy.BeginInvoke, asy.EndInvoke, (l.Count / ps), null).ContinueWith(o => Console.WriteLine(string.Format(" :{0}", o.Result)));
line = sr.ReadLine();
}
}
//WaitHandle.WaitAll();
end = DateTime.Now.Ticks;
Console.WriteLine(" =" + Convert.ToString(end - start));
Console.ReadLine();

}
}