-
您现在的位置:网络学院 > 开发教室 > 工具平台 > VC/C#
C#多线程编程实例实战

出处:PConline
责任编辑:ycx

[03-5-19 10:34] 作者:刘弹/ASPCool
-
   
测试

测试程序取自.Net FrameSDK中的一个例子,只是稍做修改。测试程序如下,

using System;

using System.Threading;

using MyThreading;

class Resource {

myReaderWriterLock rwl = new myReaderWriterLock();

public void Read(Int32 threadNum) {

rwl.AcquireReaderLock(Timeout.Infinite);

try {

Console.WriteLine("Start Resource reading (Thread={0})", threadNum);

Thread.Sleep(250);

Console.WriteLine("Stop Resource reading (Thread={0})", threadNum);

}

finally {

rwl.ReleaseReaderLock();

}

}

public void Write(Int32 threadNum) {

rwl.AcquireWriterLock(Timeout.Infinite);

try {

Console.WriteLine("Start Resource writing (Thread={0})", threadNum);

Thread.Sleep(750);

Console.WriteLine("Stop Resource writing (Thread={0})", threadNum);

}

finally {

rwl.ReleaseWriterLock();

}

}

}

class App {

static Int32 numAsyncOps = 20;

static AutoResetEvent asyncOpsAreDone = new AutoResetEvent(false);

static Resource res = new Resource();



public static void Main() {

for (Int32 threadNum = 0; threadNum < 20; threadNum++) {

ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateResource), threadNum);

}

asyncOpsAreDone.WaitOne();

Console.WriteLine("All operations have completed.");

Console.ReadLine();

}

// The callback method's signature MUST match that of a System.Threading.TimerCallback

// delegate (it takes an Object parameter and returns void)

static void UpdateResource(Object state) {

Int32 threadNum = (Int32) state;

if ((threadNum % 2) != 0) res.Read(threadNum);

else res.Write(threadNum);

if (Interlocked.Decrement(ref numAsyncOps) == 0)

asyncOpsAreDone.Set();

}

}

从测试结果中可以看出,可以满足单个写入程序\多个阅读程序的实现要求。
-

[上一页] [1] [2] [3]
发给好友 投稿给我们 加入收藏 返回顶部

相关文章:

微软添喜 C#语言通过ISO认证
C#事件及响应方法
在Linux上运行C#
用C#创建一个万年历
一步一步用Visual C#创建Web服务
在C#中编程添加前台脚本
C#网络编程概述(3)
C#网络编程概述(2)
C#网络编程概述(1)
内容搜索 
高级搜索
本栏今日焦点