gpt4 book ai didi

c# - yield return 的线程安全性(是吗?)

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

所以我有一个在不同线程上的其他 2 个类之间共享的类的公共(public)实例。让我解释一下:

public class Config
{
public IEnumerable<Regex> GetSafeRuleRegex()
{
foreach (string rule in this.SafeRules)
{
Regex regex = null;

try
{
regex = new Regex(rule, RegexOptions.IgnoreCase);
}
catch(Exception e)
{
Trace.Write(e.Message);
}

if (regex != null)
yield return regex;
}
}
}

public class Dispatcher
{
public void Start()
{
var config = new Config();

for (var i = 0; i < 10; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(o => new Item(config)));
}
}
}

这会导致锁定问题吗?

最佳答案

这里的问题似乎是您在多个线程的单个 Config 实例上调用 Config::GetSafeRuleRegex 并且想知道这是否安全。

在这种情况下,yield return 本身并没有什么危险。每个调用 GetSafeRuleRegex 的线程都将获得一个单独的迭代器实例。如果实例仅在创建它的线程上使用,那么在多个线程上创建它们是安全的。

GetSafeRuleRegex 中的其他代码可能存在一些问题。但是,它取决于 Config 的实现细节,这些细节在这个问题中并不清楚。

关于c# - yield return 的线程安全性(是吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4157771/

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