gpt4 book ai didi

c# - 根据其属性执行多/单线程操作

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:40 25 4
gpt4 key购买 nike

给定可以并行运行的操作列表,我想考虑一个或另一个操作不希望与其他操作并行执行(由属性确定 Action )。

考虑这种简化:

private static Random random;

static void Main (string[] args)
{
random = new Random();
new Thread (() => DoSomething (false)).Start();
new Thread (() => DoSomething (false)).Start();
new Thread (() => DoSomething (true)).Start();
new Thread (() => DoSomething (false)).Start();
new Thread (() => DoSomething (false)).Start();
Console.Read();

}

private static void DoSomething(bool singlethread)
{
Console.WriteLine ("Entering " + Thread.CurrentThread.ManagedThreadId);
if (singlethread)
Console.WriteLine ("Im the only one!!!");
Thread.Sleep (random.Next (1000, 5000));
Console.WriteLine ("Exiting " + Thread.CurrentThread.ManagedThreadId);
}

如何同步操作,以便操作 3 等待操作 1 和 2 退出,然后阻止操作 4 和 5?

更新

这是我在 Rob 的帮助下想出的:

public class Lock : IDisposable
{
private static readonly object _object = new object();
private static readonly AutoResetEvent _event = new AutoResetEvent (false);
private static int _count;

public static IDisposable Get (bool exclusive)
{
return new Lock (exclusive);
}

private readonly bool _wasTaken;

private Lock (bool exclusive)
{
if (exclusive)
{
Monitor.Enter (_object, ref _wasTaken);
_count++;

while (_count > 1)
_event.WaitOne();
}
else
{
lock (_object)
Interlocked.Increment (ref _count);
}
}

public void Dispose ()
{
Interlocked.Decrement (ref _count);
if (_wasTaken)
Monitor.Exit (_object);
_event.Set();
}
}

像这样使用:

using (Lock.Get(exclusive: false/true)
{
DoSomething();
}

最佳答案

代替Thread,你可以在一个特殊的调度器上启动一个Task,称为ConcurrentExclusiveSchedulerPair。 .它允许您将任务声明为并发就绪或独占。

它的工作原理与拥有 ReaderWriterLockSlim 并让并发就绪的工作项获取读锁而让独占项获取写锁的工作方式相同。

如果我正确理解您的情况,这应该可以满足您的需求,并且无需在此线程中发布的所有手动同步代码。

关于c# - 根据其属性执行多/单线程操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19778613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com