using System;
using System.Threading;
using System.Runtime.Remoting.Contexts;
namespace ConsoleApplication4
{
[Synchronization]
public class MyCounter : ContextBoundObject
{
private int _expectedCounterVal;
private int _currentCounterVal;
private ManualResetEvent _event = new ManualResetEvent(false);
public void WaitUntilCounterIs(int counterVal)
{
_expectedCounterVal = counterVal;
_event.WaitOne(TimeSpan.FromDays(1), true);
}
public void IncrementCounter()
{
if (++_currentCounterVal >= _expectedCounterVal)
{
_event.Set();
}
}
static void Main()
{
MyCounter counter = new MyCounter();
Output("Main starting.");
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkThreadAddCounter), counter);
counter.WaitUntilCounterIs(10);
Output("Main ending.");
}
static void WorkThreadAddCounter(object counter)
{
Output("Work starting.");
for (int i = 0; i < 20; i++)
{
Thread.Sleep(10);
((MyCounter)counter).IncrementCounter();
Output(i.ToString());
}
Output("Work ending.");
}
static void Output(string text)
{
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ") + text);
}
}
}
using System.Threading;
using System.Runtime.Remoting.Contexts;
namespace ConsoleApplication4
{
[Synchronization]
public class MyCounter : ContextBoundObject
{
private int _expectedCounterVal;
private int _currentCounterVal;
private ManualResetEvent _event = new ManualResetEvent(false);
public void WaitUntilCounterIs(int counterVal)
{
_expectedCounterVal = counterVal;
_event.WaitOne(TimeSpan.FromDays(1), true);
}
public void IncrementCounter()
{
if (++_currentCounterVal >= _expectedCounterVal)
{
_event.Set();
}
}
static void Main()
{
MyCounter counter = new MyCounter();
Output("Main starting.");
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkThreadAddCounter), counter);
counter.WaitUntilCounterIs(10);
Output("Main ending.");
}
static void WorkThreadAddCounter(object counter)
{
Output("Work starting.");
for (int i = 0; i < 20; i++)
{
Thread.Sleep(10);
((MyCounter)counter).IncrementCounter();
Output(i.ToString());
}
Output("Work ending.");
}
static void Output(string text)
{
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ") + text);
}
}
}