gpt4 book ai didi

c# - 迭代时从外部更改列表

转载 作者:行者123 更新时间:2023-11-30 17:43:38 25 4
gpt4 key购买 nike

我有以下代码:

    private static List<String> MyList;

static void Main()
{
MyList = new List<String>();

var websocketClient = new WebSocket("wss://ws.mysite.com");
websocketClient.MessageReceived += IterateMyList;

var updateListTimer = new Timer();
updateListTimer.Elapsed += UpdateMyList;

Console.ReadLine();
}

public static void IterateMyList(object sender, EventArgs e)
{
foreach (var item in MyList)
{
//Do Something with the item
}
}

public static void UpdateMyList(object sender, EventArgs e)
{
// Add new items to and remove items from MyList.
}

当 Timer tick 和新的 Websocket 消息事件发生冲突时会发生什么?

IterateMyList() 将迭代 MyList 并且 UpdateMyList() 将同时更新它。

我会得到异常(exception)吗?

最佳答案

当您尝试在迭代期间插入时,您将引发异常并收到一条错误消息,指出您正在尝试“读取或写入 protected 内存”。

要解决这个问题,请使用 ConcurrentBag<T>other concurrent collecton .这些Collection对象是线程安全的。如果您不关心顺序,我建议使用 ConcurrentBag出于性能原因。

关于c# - 迭代时从外部更改列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30602669/

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