- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我看到了下面的代码,想用它做一个简单的activity,一次只能执行一个,不会频繁出现(所以一次出现两次的几率很小,但是你永远不知道)。
所以代码:
// class variable
private static object syncRoot = new object();
// in a method:
lock (syncRoot)
{
DoIt();
}
当另一个线程过来要执行代码时,它要等多久才能释放锁?永远,或者你能以某种方式设置超时吗?
其次:如果 DoIt()
方法抛出异常,锁是否仍然释放?
最佳答案
When another thread comes by and wants to execute the code, how long will it wait until the lock is released?
lock
将无限期地阻止试图进入锁的线程,直到被锁定的对象被释放。
can you somehow set a timeout?
如果需要指定超时,请使用 Monitor.TryEnter
如
if(Monitor.TryEnter(obj, new TimeSpan(0, 0, 1))) {
try {
body
}
finally {
Monitor.Exit(obj);
}
}
if the
DoIt()
method throws an exception, is the lock still released?
是的,一个 lock(obj) { body }
被翻译成:
bool lockWasTaken = false;
var temp = obj;
try { Monitor.Enter(temp, ref lockWasTaken); { body } }
finally { if (lockWasTaken) Monitor.Exit(temp); }
有关抛出异常时会发生什么的详细信息,请参阅 Locks and exceptions do not mix .
关于c# - C# 锁定将等待多长时间,如果代码在锁定期间崩溃怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6049346/
我有一个独立的 Thread 应用程序。这是一个等待消息的监听器,当消息到达时执行一些操作,其中我必须将消息保存在数据库中。但我遇到了问题,因为如果我运行应用程序并“手动发送消息”,一切都会正常工作,
我有以下php代码: sleep(65); $query = "UPDATE database.table SET XXXXXXX = XXXXXXX - ".$YYYYYY." WHERE
我正在开发一个业余爱好应用程序。它在主布局中使用 webview。单击 webview 内的链接会使用户保持在 webview 内。启动后一切正常,但仍在应用程序内。但是,在手机休眠一段时间后,我重新
我目前运行的应用程序需要最大堆大小为 16GB。 目前我使用以下标志来处理垃圾回收。 -XX\:+UseParNewGC, -XX\:+UseConcMarkSweepGC, -XX:CMSIniti
$ uname -a Darwin Wheelie-Cyberman 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011
在 while 循环仍在休眠时退出它的最简单方法是什么?是否有某种函数可以在 sleep 时检测某个值是否为真? 或者我是否在循环中设置一个小 sleep 并检查如果不再睡一会儿就退出?如果可以,我该
我正在 Ubunu 的 Jetty 6 上运行 Java Web 服务器,用于基于反向 ajax 的 Web。而且我在向浏览器重新发送数据的线程滞后方面遇到了严重的问题。很多时候,一些线程开始 hib
当我运行长时间操作时,我遇到来自 IIS 的请求超时。我的 ASP.NET 应用程序正在后台处理数据,但处理的记录数量很大,因此操作需要很长时间。 但是,我认为 IIS 使 session 超时。这是
我不确定从哪里开始解决这个问题,但如果我有一个 AJAX 网络应用程序向服务器发送请求并在数据库(在我的例子中是 postgresql)上运行长查询,有没有办法停止或如果仍在运行时用户刷新页面或关闭
我是一名优秀的程序员,十分优秀!