Skip to content

Instantly share code, notes, and snippets.

@munron
Created September 6, 2016 01:47
Show Gist options
  • Save munron/c2b2fc43e5c59f72630a2df35d500deb to your computer and use it in GitHub Desktop.
Save munron/c2b2fc43e5c59f72630a2df35d500deb to your computer and use it in GitHub Desktop.
C# デリゲート入門 3
using System;
//デリゲートを使った同期、非同期処理のサンプルコード
namespace ConsoleApplication9
{
delegate double AsyncSum(double n);
class Program
{
static void Main(string[] args)
{
AsyncSum asyncSum = sum;
Console.WriteLine(asyncSum.Invoke(1000000000));
//同期処理なので上の処理が終わるまで次に進まない
Console.WriteLine("同期処理の場合");
Console.WriteLine("------------------------------------------------");
IAsyncResult ar =asyncSum.BeginInvoke(1000000000,null,null);
//非同期処理なので上の処理は別スレッドで実行され、戻り値が得られる前に次の処理に進む
Console.WriteLine("非同期処理の場合");
Console.WriteLine(asyncSum.EndInvoke(ar));
Console.ReadKey();
}
//時間のかかる処理
public static double sum(double n)
{
double result = 0;
for (double i = 0; i < n; i++)
{
result += i;
}
return result;
}
}
}
/*
* まとめ
* 同期的に呼び出す場合はInvokeメソッド
* 非同期に呼び出す場合はBeginInvokeメソッド
* 非同期呼び出しの処理終了を待って戻り値を得るにはEndInvokeメソッド
* /
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment