这是什么以及如何使用?
What is it and how to use?
我需要为我有插入到数据库每一秒的计时器,我有定时器处理程序,并在主线程之间共享的资源。我想出示担保,如果定时器的处理程序需要超过一秒的插入的等待线程应该在顺序执行。这是一个示例code代表我的定时器处理程序
I need that as I have a timer that inserts into DB every second, and I have a shared resource between timer handler and the main thread. I want to gurantee that if the timer handler takes more than one second in the insertion the waited threads should be executed in order. This is a sample code for my timer handler
private void InsertBasicVaraibles(object param) { try { DataTablesMutex.WaitOne();//mutex for my shared resources //insert into DB } catch (Exception ex) { //Handle } finally { DataTablesMutex.ReleaseMutex(); } }但目前互斥体不保证任何顺序。我把具体问题后,没有回答!
But currently the mutex does not guarantee any order. There is not answer after I put the detailed question!!!
推荐答案您需要编写自己的类要做到这一点,我发现这个例子中(粘贴,因为它看起来好像网站的域名已经失效):
You'll need to write your own class to do this, I found this example (pasted because it looks as though the site's domain has lapsed):
using System.Threading; public sealed class QueuedLock { private object innerLock; private volatile int ticketsCount = 0; private volatile int ticketToRide = 1; public QueuedLock() { innerLock = new Object(); } public void Enter() { int myTicket = Interlocked.Increment(ref ticketsCount); Monitor.Enter(innerLock); while (true) { if (myTicket == ticketToRide) { return; } else { Monitor.Wait(innerLock); } } } public void Exit() { Interlocked.Increment(ref ticketToRide); Monitor.PulseAll(innerLock); Monitor.Exit(innerLock); } }使用示例:
QueuedLock queuedLock = new QueuedLock(); try { queuedLock.Enter(); // here code which needs to be synchronized // in correct order } finally { queuedLock.Exit(); }Source通过谷歌缓存
更多推荐
是否有保证C#FIFO顺序同步类?
发布评论