c# – 使用字典的不安全线程 – 让我们打破一些东西
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用字典的不安全线程 – 让我们打破一些东西,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1728字,纯文字阅读大概需要3分钟。
内容图文
![c# – 使用字典的不安全线程 – 让我们打破一些东西](/upload/InfoBanner/zyjiaocheng/758/bc4dfeed5b8147d28d563d2d22706612.jpg)
所以在http://msdn.microsoft.com/en-us/library/xfhwa508.aspx的底部我们看到了
A Dictionary(Of TKey, TValue) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
在我的asp.net应用程序中,我偶尔会看到从System.Collections.Generic.Dictionary`2.Insert内部生成的NullReferenceExceptions.
我怎么能在沙盒中重新创建它?
尽管本地字典由单独的线程访问,但以下代码不会导致异常.
class Program {
static void Main(string[] args) {
int maxThreads = 20;
Dictionary<Guid, Guid> dict = new Dictionary<Guid, Guid>();
var tws = new threadWithState();
while (true) {
for (int i = 0; i < maxThreads * 2; i++) {
var thread = new Thread(tws.Work);
thread.IsBackground = true;
thread.Start(dict);
}
dict[Guid.NewGuid()] = Guid.NewGuid();
}
}
}
class threadWithState {
public void Work(object dict) {
Console.WriteLine((dict as Dictionary<Guid, Guid>).Count);
for (int i = 0; i < 1000; i++) {
(dict as Dictionary<Guid, Guid>)[Guid.NewGuid()] = Guid.NewGuid();
}
}
}
解决方法:
由于垃圾收集堆锁,此代码遭受意外同步.通过注入随机延迟,您可以更快地崩溃,就像在实际服务器上发生的那样.这段代码让我在我的机器上崩溃了几分之一秒,ymmv:
public void Work(object dict) {
var rnd = new Random();
Console.WriteLine((dict as Dictionary<Guid, Guid>).Count);
for (int i = 0; i < 1000000; i++) {
(dict as Dictionary<Guid, Guid>)[Guid.NewGuid()] = Guid.NewGuid();
for (int ix = 0; ix < rnd.Next(1000); ++ix) ; // NOTE: random delay
}
}
内容总结
以上是互联网集市为您收集整理的c# – 使用字典的不安全线程 – 让我们打破一些东西全部内容,希望文章能够帮你解决c# – 使用字典的不安全线程 – 让我们打破一些东西所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。