请教一个多线程的问题,对象加锁,有些地方不明白,高手帮忙看看 本帖最后由 rija0026 于 2010-12-02 12:23:44 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 简单的生产者,消费者同步控制,通过Event进行同步读写控制public class DataObject { public long IntValue { get; set; } public string StrValue { get; set; } } class Program { static AutoResetEvent writeEvent = new AutoResetEvent(true); static AutoResetEvent readEvent = new AutoResetEvent(false); static DataObject dataObject = new DataObject(); static void Main() { //Write Thread ThreadPool.QueueUserWorkItem(status => { while (true) { if (writeEvent.WaitOne(1)) { dataObject.IntValue = DateTime.Now.Ticks; dataObject.StrValue = Guid.NewGuid().ToString(); Console.WriteLine("Write:{0},{1}", dataObject.IntValue, dataObject.StrValue); readEvent.Set(); } } }, null); //Read Thread ThreadPool.QueueUserWorkItem(status => { while (true) { if (readEvent.WaitOne(1)) { Console.WriteLine("Read:{0},{1}", dataObject.IntValue, dataObject.StrValue); writeEvent.Set(); } } }, null); Console.Read(); } }你也可以使用系统提供的ReaderWriterLock类去实现类似的功能 c# 如何实现弹出usb 字符串转换为其它类型... 如何在.net2005里创建一个c#.net程序 问一个 C#如何读取和修改".cfg配置文件" 的问题 帮我看看~~~~ 热烈祝贺"<MISGoldPrinter>(MIS金质打印王)"免费C#.NET源码版通过中国共享软件注册中心审核通过!!! int ? page 国内第一款专业的矢量动画制作软件即将发布,基于SVG,采用C#开发 如何实现气泡窗口? Git下载的类库怎么使用 检查word文件格式的系统的原理? 求教 object reference not set to an instance of an object 问题
public class DataObject
{
public long IntValue { get; set; }
public string StrValue { get; set; }
} class Program
{
static AutoResetEvent writeEvent = new AutoResetEvent(true);
static AutoResetEvent readEvent = new AutoResetEvent(false); static DataObject dataObject = new DataObject();
static void Main()
{
//Write Thread
ThreadPool.QueueUserWorkItem(status =>
{
while (true)
{
if (writeEvent.WaitOne(1))
{
dataObject.IntValue = DateTime.Now.Ticks;
dataObject.StrValue = Guid.NewGuid().ToString();
Console.WriteLine("Write:{0},{1}", dataObject.IntValue, dataObject.StrValue);
readEvent.Set();
}
}
}, null);
//Read Thread
ThreadPool.QueueUserWorkItem(status =>
{
while (true)
{
if (readEvent.WaitOne(1))
{
Console.WriteLine("Read:{0},{1}", dataObject.IntValue, dataObject.StrValue);
writeEvent.Set();
}
}
}, null); Console.Read();
}
}
你也可以使用系统提供的ReaderWriterLock类去实现类似的功能