【发布时间】:2018-12-24 13:56:22
【问题描述】:
我正在尝试动态锁定线程,但无论我尝试什么,总是会发生某种竞争条件,这似乎是由多个线程同时启动任务引起的,但我一直无法找到很好的答案。
这是一个例子:
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static readonly Object padLock = new Object();
public readonly static ConcurrentDictionary<string, object> locks = new
ConcurrentDictionary<string, object>();
public static List<string> processes = new List<string>();
public static void Main()
{
//Add random list of processes (just testing with one for now)
for (var i = 0; i < 1; i++) {
processes.Add("random" + i.ToString());
}
while (true)
{
foreach (var process in processes )
{
var currentProc = process ;
lock (padLock)
{
if (!locks.ContainsKey(currentProc))
{
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
if (!locks.ContainsKey(currentProc))
{
var lockObject = locks.GetOrAdd(currentProc, new object());
lock (lockObject)
{
Console.WriteLine("Currently Executing " + currentProc);
Console.WriteLine("Ended Executing " + currentProc);
((IDictionary)locks).Remove(currentProc);
}
}
});
}
}
// Thread.Sleep(0);
}
}
Console.ReadLine();
}
}
输出:
Started 1
Finished 1
Started 1
Finished 1
Started 1
Finished 1
但有时会得到:
Started 1
Started 1
Finished 1
这是不希望的,动态锁应该锁定它并只执行一次
【问题讨论】:
-
hrmm
Started没有在你的代码中表示,只是说 -
你想完成什么OP?如果您只想确保每个对象只处理一次,那么这是一种非常不寻常的模式。
-
@TheGeneral Started 当前正在执行
-
@JohnWu 你会怎么做?
-
我们不知道您要做什么。这样做的目的是什么?
标签: c# multithreading parallel-processing thread-safety threadpool