C#_delegate-非同期呼び出しインスタンスBeginInvoke EndInvoke event
2735 ワード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace EventClock
{
public class ClassWithDelegate
{
// int
public delegate int DelegateThatReturns();
public event DelegateThatReturns theDelegate;
public void Run()
{
for (; ; )
{
Thread.Sleep(500);
if (theDelegate != null)
{
//
foreach (DelegateThatReturns del in theDelegate.GetInvocationList())
{
//
//
del.BeginInvoke(new AsyncCallback(ResultReturns), del);
}
Console.WriteLine();
}
}
}
//
public void ResultReturns(IAsyncResult iar)
{
//
DelegateThatReturns del = (DelegateThatReturns)iar.AsyncState;
// EndInvoke
int result = del.EndInvoke(iar);
//
Console.WriteLine("Delegate returned result: {0}",result);
}
}
public class FirstSubscribe
{
private int myCounter = 0;
public void Subscribe(ClassWithDelegate theClassWithDelegate)
{
theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturns(DisplayCounter);
}
public int DisplayCounter()
{
Console.WriteLine("Busy in displaying............");
Thread.Sleep(10000);
Console.WriteLine("Do not with work in display............");
return ++myCounter;
}
}
public class SecondSubscribe
{
private int myCounter = 0;
public void Subscribe(ClassWithDelegate theClassWithDelegate)
{
theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturns(Doubler);
}
public int Doubler()
{
return myCounter += 2;
}
}
class Program
{
static void Main(string[] args)
{
ClassWithDelegate theClassWithDelegate = new ClassWithDelegate();
FirstSubscribe fs = new FirstSubscribe();
fs.Subscribe(theClassWithDelegate);
SecondSubscribe ss = new SecondSubscribe();
ss.Subscribe(theClassWithDelegate);
theClassWithDelegate.Run();
Console.ReadLine();
}
}
}