我有以下代码:
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()将同时更新它。
我会得到例外吗?
答案 0 :(得分:1)
当您尝试在迭代期间插入时,您将引发异常并收到错误消息,指出您正在尝试“读取或写入受保护的内存”。
要解决此问题,请使用ConcurrentBag<T>
或other concurrent collecton。这些Collection
对象是线程安全的。如果您不关心订单,我建议您出于性能原因使用ConcurrentBag
。