线程操作问题

lshfong 2007-05-25 09:05:44
现有两个线程a和b,操作的是同一个文件,怎么样才能保证,a线程操作完毕后才启动b线程进行操作.
...全文
219 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wenbin 2007-05-25
  • 打赏
  • 举报
回复
using System;
using System.Threading;


class Resource {
Mutex m = new Mutex();

public void Access(Int32 threadNum) {
m.WaitOne();
try {
Console.WriteLine("Start Resource access (Thread={0})", threadNum);
Thread.Sleep(500);
Console.WriteLine("Stop Resource access (Thread={0})", threadNum);
}
finally {
m.ReleaseMutex();
}
}
}


class App {
static Int32 numAsyncOps = 5;
static AutoResetEvent asyncOpsAreDone = new AutoResetEvent(false);
static Resource res = new Resource();

public static void Main() {
for (Int32 threadNum = 0; threadNum < 5; threadNum++) {
ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateResource), threadNum);
}

asyncOpsAreDone.WaitOne();
Console.WriteLine("All operations have completed.");
}


// 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) {
res.Access((Int32) state);
if (Interlocked.Decrement(ref numAsyncOps) == 0)
asyncOpsAreDone.Set();
}
}
VS自己带的例子,
wenbin 2007-05-25
  • 打赏
  • 举报
回复
用AutoResetEvent 去做
详细资料可以查msdn
lshfong 2007-05-25
  • 打赏
  • 举报
回复
还是不明白,给个例子好吗
viena 2007-05-25
  • 打赏
  • 举报
回复
那何必用两个线程?
调用Join,可以阻塞当前线程直到那个线程结束
lshfong 2007-05-25
  • 打赏
  • 举报
回复
详细一点,好吗,谢谢
wuxing2006 2007-05-25
  • 打赏
  • 举报
回复
lock

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧