僵局.NET样? [英] Deadlock sample in .net?

查看:86
本文介绍了僵局.NET样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以给C#一个简单的死锁示例代码?并请告诉最简单的方式找到僵局C#代码样本。 (可能是工具,它会检测在给定的示例代码中的死锁。)

Can anybody give a simple Deadlock sample code in c# ? And please tell the simplest way to find deadlock in your C# code sample. (May be the tool which will detect the dead lock in the given sample code.)

请注意:我有VS 2008

NOTE: I have VS 2008

推荐答案

一个共同的方法是,如果你嵌套未以相同的顺序获取的锁。 。线程1可能获取锁A和线程2可能获取锁B,他们将死锁

one common way is if you have nested locks that aren't acquired in the same order. Thread 1 could acquire lock A and thread 2 could acquire lock B and they would deadlock.

var a = new object();
var b = new object();

lock(a) {
   lock(b) {

   }
}

// other thread
lock (b) { 
  lock(a) {

  }
}

编辑:使用waithandles无锁的例子..。假设苏格拉底和笛卡尔遇到的牛排和他们俩,是彬彬有礼的哲学家,同时需要一个叉,为了吃一把刀。但是,他们只有一套银器,所以它有可能为每抢到一个用具,然后等待永远为对方交出他们的器具。

edit: non-lock example .. using waithandles. Suppose Socrates and Descartes are having steaks and they both, being well-mannered philosophers, require both a fork and a knife in order to eat. However, they have only one set of silverware, so it is possible for each to grab one utensil and then wait forever for the other to hand over their utensil.

查看餐饮哲学家的问题

WaitHandle fork = new AutoResetEvent(), knife = new AutoResetEvent();

while(Socrates.IsHungry) {
   fork.WaitOne();
   knife.WaitOne();
   Eat();
   fork.Set();
   knife.Set();
} 

// other thread
while(Descartes.IsHungry) {
   knife.WaitOne();
   fork.WaitOne();
   Eat();
   knife.Set();
   fork.Set();
} 

这篇关于僵局.NET样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆