是否有保证C#FIFO顺序同步类?

编程入门 行业动态 更新时间:2024-10-26 16:21:24
本文介绍了是否有保证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(); }

Source通过谷歌缓存

更多推荐

是否有保证C#FIFO顺序同步类?

本文发布于:2023-11-06 07:58:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563128.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   FIFO

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!