Tag:开源 , 源码下载 , 控件 , 控件开发 , 皮肤 , Skin , Socket , 水印 , QQ表情 , 透明控件 , 异步编程 , 多线程编程 , WebService , WCF , WPF , Ribbon , 数据库 , SQL , WinForm教程 , SQLite , 接口 , 抽象类 , 设计模式 , 架构 , 插件 , Visual Studio , P/Invoke , 微软提供的.Net线程池以及跨线程同步示例
 CS Windows 程序员之窗
 
您的位置: >> 首页 >> C# 博文 >> 微软提供的.Net线程池及跨线程同步示例

微软提供的.Net线程池及跨线程同步示例

2010-07-26  来自:博客园  字体大小:【  
  • 摘要:本文给出两个微软提供的.Net线程池及跨线程同步示例

.Net线程池示例:

 

public class Fibonacci
{
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n
= n;
_doneEvent
= doneEvent;
}

// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine(
"thread {0} started...", threadIndex);
_fibOfN
= Calculate(_n);
Console.WriteLine(
"thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}

// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}

return Calculate(n - 1) + Calculate(n - 2);
}

public int N { get { return _n; } }
private int _n;

public int FibOfN { get { return _fibOfN; } }
private int _fibOfN;

private ManualResetEvent _doneEvent;
}
public class ThreadPoolExample
{
static void Main()
{
const int FibonacciCalculations = 10;

// One event is used for each Fibonacci object
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray
= new Fibonacci[FibonacciCalculations];
Random r
= new Random();

// Configure and launch threads using ThreadPool:
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i]
= new ManualResetEvent(false);
Fibonacci f
= new Fibonacci(r.Next(20, 40), doneEvents[i]);
fibArray[i]
= f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
}

// Wait for all threads in pool to calculation...
WaitHandle.WaitAll(doneEvents);
Console.WriteLine(
"All calculations are complete.");

// Display the results...
for (int i = 0; i < FibonacciCalculations; i++)
{
Fibonacci f
= fibArray[i];
Console.WriteLine(
"Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
Console.Read();
}
}

 

跨线程同步示例:

 

public class SyncEvents
{
public SyncEvents()
{

_newItemEvent
= new AutoResetEvent(false);
_exitThreadEvent
= new ManualResetEvent(false);
_eventArray
= new WaitHandle[2];
_eventArray[
0] = _newItemEvent;
_eventArray[
1] = _exitThreadEvent;
}

public EventWaitHandle ExitThreadEvent
{
get { return _exitThreadEvent; }
}
public EventWaitHandle NewItemEvent
{
get { return _newItemEvent; }
}
public WaitHandle[] EventArray
{
get { return _eventArray; }
}

private EventWaitHandle _newItemEvent;
private EventWaitHandle _exitThreadEvent;
private WaitHandle[] _eventArray;
}
public class Producer
{
public Producer(Queue<int> q, SyncEvents e)
{
_queue
= q;
_syncEvents
= e;
}
// Producer.ThreadRun
public void ThreadRun()
{
int count = 0;
Random r
= new Random();
while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))
{
lock (((ICollection)_queue).SyncRoot)
{
while (_queue.Count < 20)
{
_queue.Enqueue(r.Next(
0, 100));
_syncEvents.NewItemEvent.Set();
count
++;
}
}
}
Console.WriteLine(
"Producer thread: produced {0} items", count);
}
private Queue<int> _queue;
private SyncEvents _syncEvents;
}
public class Consumer
{
public Consumer(Queue<int> q, SyncEvents e)
{
_queue
= q;
_syncEvents
= e;
}
// Consumer.ThreadRun
public void ThreadRun()
{
int count = 0;
while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)
{
lock (((ICollection)_queue).SyncRoot)
{
int item = _queue.Dequeue();
}
count
++;
}
Console.WriteLine(
"Consumer Thread: consumed {0} items", count);
}
private Queue<int> _queue;
private SyncEvents _syncEvents;
}
public class ThreadSyncSample
{
private static void ShowQueueContents(Queue<int> q)
{
lock (((ICollection)q).SyncRoot)
{
foreach (int item in q)
{
Console.Write(
"{0} ", item);
}
}
Console.WriteLine();
}

static void Main()
{
Queue
<int> queue = new Queue<int>();
SyncEvents syncEvents
= new SyncEvents();

Console.WriteLine(
"Configuring worker threads...");
Producer producer
= new Producer(queue, syncEvents);
Consumer consumer
= new Consumer(queue, syncEvents);
Thread producerThread
= new Thread(producer.ThreadRun);
Thread consumerThread
= new Thread(consumer.ThreadRun);

Console.WriteLine(
"Launching producer and consumer threads...");
producerThread.Start();
consumerThread.Start();

for (int i = 0; i < 4; i++)
{
Thread.Sleep(
2500);
ShowQueueContents(queue);
}

Console.WriteLine(
"Signaling threads to terminate...");
syncEvents.ExitThreadEvent.Set();

producerThread.Join();
consumerThread.Join();
Console.Read();
}

}
作者:瞌睡虫
上一篇:多线程编程中的锁定(Mutex)      
相关文章:
该文章已有条评论 我要发表评论
Website Statisticsflip hd camcorder