是否有保证C#FIFO顺序同步类? [英] Is there a synchronization class that guarantee FIFO order in C#?

查看:119
本文介绍了是否有保证C#FIFO顺序同步类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么以及如何使用?

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();
}

<一个href=\"http://209.85.229.132/search?q=cache:81M3MdpllfEJ:jakubsloup.cz/Blog/March-2009/Monitor-lock-which-remember-order-in-C--to-simulat.aspx\">Source通过谷歌缓存

这篇关于是否有保证C#FIFO顺序同步类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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