关键词搜索

源码搜索 ×
×

C# Dictionary多线程安全访问问题

发布2018-06-01浏览12135次

详情内容

Dictionary是非线程安全的类型,操作的时候需要对其进行线程安全处理,最简单的方式就是加锁(lock)。

数据变量:

private static Dictionary<string, VirtualVideoChannel> m_list_video_channel_all = new Dictionary<string, VirtualVideoChannel>();

加锁代码:

  1. /// <summary>
  2. /// 创建设备通道连接
  3. /// </summary>
  4. /// <param name="sim"></param>
  5. private void CreateNewChannelConnection(string sim)
  6. {
  7. var m_tcp_order = new Network.TCPChannel(txtServer.Text.Trim(), Convert.ToInt32(numPort.Value));
  8. // 设置Tag为SIM卡号
  9. m_tcp_order.Tag = sim;
  10. m_tcp_order.DataReceive = Receive;
  11. m_tcp_order.DataSend = DataSend;
  12. m_tcp_order.ChannelConnect += channel_ChannelConnect;
  13. m_tcp_order.Connect();
  14. // 映射SIM号和连接对象
  15. lock (m_sim_dictionary)
  16. {
  17. if (m_sim_dictionary.ContainsKey(sim))
  18. {
  19. TCPChannel tcpChannel;
  20. m_sim_dictionary.TryGetValue(sim, out tcpChannel);
  21. if (tcpChannel != null)
  22. {
  23. tcpChannel.Close();
  24. m_sim_dictionary.Remove(sim);
  25. }
  26. }
  27. m_sim_dictionary.Add(sim, m_tcp_order);
  28. }
  29. }
同样的,List也不是线程安全的,同样都需要如此处理,当然可以换成别的方式来做。

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载