线程间通信的同步机制(ConcurrentQueue)

假设需要实现的功能:

创建两个线程,一个用来读取数据,一个用来更新数据。

使用 ConcurrentQueue 来存放读取到的数据,然后使用 TryTake 或者 TryDequeue 来判断队列是否有新数据,如果有则更新 UI。

csharp 复制代码
private readonly ConcurrentQueue<string> _dataQueue = new ConcurrentQueue<string>();

private void DataReadingThread()
{
    while (true)
    {
        string data = ReadData();
        if (!_dataQueue.Contains(data))
        {
            _dataQueue.Enqueue(data);
        }
    }
}

private void UIUpdateThread()
{
    while (true)
    {
        if (_dataQueue.TryDequeue(out string newData))
        {
            Dispatcher.Invoke(() =>
            {
                // 更新UI元素
                // myLabel.Content = newData;
            });
        }
    }
}

注意:

队列的原则是先进先出

读取数据的线程是一直往队列中存放数据的,为了保证更新的数据是最新的数据,更新UI的频率需要高于读取数据的频率,否则就会出现队列堆积数据,导致UI数据更新不及时的问题。

相关推荐
钟灵92115 小时前
C++【模板初阶】
开发语言·c++·笔记·c#
专注VB编程开发20年16 小时前
C#,VB.NET 生成debug日志文件
服务器·数据库·c#
AI刀刀16 小时前
文心粘贴到 word 格式混乱,AI 导出鸭智能转文档零失真
人工智能·c#·word·ai导出鸭
WarPigs1 天前
C# dll笔记
c#
淡笑沐白1 天前
C# HttpClient完整使用指南
c#·httpclient
JaydenAI1 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
小满Autumn1 天前
MVVM Light 架构笔记:定位器、命令、消息与 IoC 实践
笔记·学习·架构·c#·上位机·mvvm
小满Autumn1 天前
CommunityToolkit.Mvvm 架构笔记:现代 MVVM、源生成器与工程化实践
笔记·架构·c#·.net·wpf·mvvm
加号31 天前
【C#】 JSON 序列化与反序列化:从入门到最佳实践
c#·json
胖纸不争1 天前
自建 Copilot Cli 代理:让 GitHub Copilot 真正"Bring Your Own Key"
ai·c#