2016年1月28日 星期四

C17_10 AutoResetEvent類別的事件 ThreadTask.cs

using System;
using System.Threading;
public struct InputData
{
    public int X;
    public int Y;
    public InputData(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }
}
public class ThreadTask
{
    private AutoResetEvent autoEvent;
    private int result;
    public int Result
    {
        get { return result; }
    }
    public ThreadTask(AutoResetEvent ev)
    {
        this.autoEvent = ev;
    }
    public void Calculation(object obj)
    {
        InputData data = (InputData)obj;
        Console.WriteLine("Thread {0} starts calculation", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(new Random().Next(3000));
        result = data.X + data.Y;
        Console.WriteLine("Thread {0} is ready", Thread.CurrentThread.ManagedThreadId);
        autoEvent.Set();
    }

}

沒有留言: