110,539
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication18
{
class Program
{
static void Main(string[] args)
{
AutoResetEvent waitHandle = new AutoResetEvent(false);
//start other thread
Worker worker = new Worker();
worker.DoSomeWork(waitHandle);
//let main UI thread so some processing
Console.WriteLine("Main thread working");
Thread.Sleep(5000);
Console.WriteLine("Main thread finished work, let other thread
continue");
waitHandle.Set();
Console.ReadLine();
}
}
class Worker
{
private WaitHandle waitHandle;
public void DoSomeWork(WaitHandle waitHandle)
{
this.waitHandle = waitHandle;
Thread t = new Thread(new ThreadStart(ProcessValues));
t.Start();
}
private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLine("processing:" + i);
}
//make sure I am allowed to keep going
this.waitHandle.WaitOne();
//Can only run this once main thread is happy
for (int i = 0; i < 5; i++)
{
Console.WriteLine("last processing:" + i);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication18
{
class Program
{
static void Main(string[] args)
{
AutoResetEvent waitHandle = new AutoResetEvent(false);
//start other thread
Worker worker = new Worker();
worker.DoSomeWork(waitHandle);
//let main UI thread so some processing
Console.WriteLine("Main thread working");
Thread.Sleep(5000);
Console.WriteLine("Main thread finished work, let other thread
continue");
waitHandle.Set();
Console.ReadLine();
}
}
class Worker
{
private WaitHandle waitHandle;
public void DoSomeWork(WaitHandle waitHandle)
{
this.waitHandle = waitHandle;
Thread t = new Thread(new ThreadStart(ProcessValues));
t.Start();
}
private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLine("processing:" + i);
}
//make sure I am allowed to keep going
this.waitHandle.WaitOne();
//Can only run this once main thread is happy
for (int i = 0; i < 5; i++)
{
Console.WriteLine("last processing:" + i);
}
}
}
}