更新记录

本文迁移自Panda666原博客,原发布时间:2021年7月1日。

一、并发集合

.NET中提供了相当多线程安全的集合,它们都在System.Collections.Concurrent命名空间下。具体的类型进行可以到.NET官方API浏览器:点击这里访问查看。

具体类型如下:

二、多任务写入/读取ConcurrentQueue

这里使用支持并发的队列ConcurrentQueue作为例子,通过2个Task进行进队任务,再通过2个Task进行出队的任务。

using System;
using System.Threading.Tasks;
using System.Collections.Concurrent; namespace PadnaTestClass
{
class Program
{
static void Main(string[] args)
{ //用于写入的集合
ConcurrentQueue<string> concurrentQueue = new ConcurrentQueue<string>(); //=========================进队操作==========================
//新建进队任务1
Task taskForEnqueue1 = Task.Run(() => {
for (int i = 0; i <= 10000; i++)
{
//存入和输出的内容
string content = $"进队任务1,当前执行到{i}";
//进队
concurrentQueue.Enqueue(content);
//输出操作过程
Console.WriteLine(content);
}
}); //新建进队任务2
Task taskForEnqueue2 = Task.Run(() => {
for (int i = 0; i <= 10000; i++)
{
//存入和输出的内容
string content = $"进队任务2,当前执行到{i}";
//进队
concurrentQueue.Enqueue(content);
//输出操作过程
Console.WriteLine(content);
}
}); //等待写入任务完成
Task.WaitAll(new Task[] { taskForEnqueue1, taskForEnqueue2 });
//=========================进队操作========================== //=========================出队操作===================
//新建出队任务1
Task taskForDequeue1 = Task.Run(() => {
while (concurrentQueue.Count != 0)
{
if (concurrentQueue.TryDequeue(out string result))
{
Console.WriteLine("出队任务1-" + result);
}
}
}); //新建出队任务2
Task taskForDequeue2 = Task.Run(() => {
while (concurrentQueue.Count != 0)
{
if (concurrentQueue.TryDequeue(out string result))
{
Console.WriteLine("出队任务2-" + result);
}
}
});
//=========================出队操作==================== //wait
Console.ReadKey();
}
}
}
``` ### 三、多任务写入/读取ConcurrentDictionary
这里使用支持并发的字典ConcurrentDictionary作为例子,通过2个Task进行写入元素数据任务,再通过2个Task进行读取和移除元素的任务。
```c#
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent; namespace PadnaTestClass
{
class Program
{
static void Main(string[] args)
{
//用于写入的集合
ConcurrentDictionary<string,string> concurrentDictionary = new ConcurrentDictionary<string,string>(); //==========添加数据操作=================
//新建用于写入数据的任务1
Task taskForAddData1 = Task.Run(() => {
for (int i = 0; i <= 10000; i++)
{
//存入和输出的内容
string dataKey = $"任务1的-{i}-Key";
string dataValue = $"任务1的-{i}-Value";
//加入数据到并发集合中
concurrentDictionary.TryAdd(dataKey, dataValue);
//输出操作过程
Console.WriteLine(dataKey + " || " + dataValue);
}
}); //新建用于写入数据的任务2
Task taskForAddData2 = Task.Run(() => {
for (int i = 0; i <= 10000; i++)
{
//存入和输出的内容
string dataKey = $"任务2的-{i}-Key";
string dataValue = $"任务2的-{i}-Value";
//加入数据到并发集合中
concurrentDictionary.TryAdd(dataKey, dataValue);
//输出操作过程
Console.WriteLine(dataKey + " || " + dataValue);
}
}); //等待写入任务完成
Task.WaitAll(new Task[] { taskForAddData1, taskForAddData2 });
//==============添加数据操作=================
//=============读取并移除数据操作============
//新建读取并删除元素任务1
Task taskForReadData1 = Task.Run(() => {
foreach (string dataKey in concurrentDictionary.Keys)
{
if (concurrentDictionary.TryGetValue(dataKey, out string dataValue))
{
//输出值
Console.WriteLine(dataValue);
//移除值
concurrentDictionary.TryRemove(new KeyValuePair<string, string>(dataKey,dataValue));
}
}
}); //新建读取并删除元素任务2
Task taskForReadData2 = Task.Run(() => {
foreach (string dataKey in concurrentDictionary.Keys)
{
if (concurrentDictionary.TryGetValue(dataKey, out string dataValue))
{
//输出值
Console.WriteLine(dataValue);
//移除值
concurrentDictionary.TryRemove(new KeyValuePair<string, string>(dataKey, dataValue));
}
}
});
//==========读取并移除数据操作========= //等待任务完成
Task.WaitAll(taskForReadData1, taskForReadData2);
//读取集合元素的个数
Console.WriteLine(concurrentDictionary.Count); //0 //wait
Console.ReadKey();
}
}
}

.NET中的并发操作集合的更多相关文章

  1. Java中的并发编程集合使用

    一.熟悉Java自带的并发编程集合 在java.util.concurrent包里有很多并发编程的常用工具类. package com.ietree.basicskill.mutilthread.co ...

  2. loadrunner 并发操作集合点配置

    在loadrunner的虚拟用户中,术语concurrent(并发)和simultaneous(同时)存在一些区别,concurrent 是指虚拟场景中参于运行的虚拟用户.而simultaneous与 ...

  3. Django中管理并发操作

    上一篇我们说了,如何在Django中进行事务操作,数据的原子性操作 涉及了事务操作,我们不得不考虑的另一个问题就是:并发操作 还是那个用户转账的操作 我们使用事务操作解决的操作中途服务器宕机问题 但是 ...

  4. MongoDB学习(操作集合中的文档)

    文档概念 文档的数据结构和JSON基本一样. 所有存储在集合中的数据都是BSON格式. BSON是一种类json的一种二进制形式的存储格式,简称Binary JSON. 插入文档 insert()方法 ...

  5. HashMap在JDK1.8中并发操作,代码测试以及源码分析

    HashMap在JDK1.8中并发操作不会出现死循环,只会出现缺数据.测试如下: package JDKSource; import java.util.HashMap; import java.ut ...

  6. java高并发系列 - 第21天:java中的CAS操作,java并发的基石

    这是java高并发系列第21篇文章. 本文主要内容 从网站计数器实现中一步步引出CAS操作 介绍java中的CAS及CAS可能存在的问题 悲观锁和乐观锁的一些介绍及数据库乐观锁的一个常见示例 使用ja ...

  7. Java并发--Java中的CAS操作和实现原理

    版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/CringKong/article/deta ...

  8. 操作集合的工具类:Collections

    Java提供了一个操作Set.List和Map等集合的工具类:Collections,该工具类提供了大量方法对集合进行排序.查询和修改等操作,还提供了将集合对象置为不可变.对集合对象实现同步控制等方法 ...

  9. 09_Java8操作集合的一些新特性

    [使用forEach()结合Lambda表达式遍历集合] public class ForEachDemo { public static void main(String[] args) { Col ...

随机推荐

  1. tkinter GUI编程

    tkinter编程概述 tkinter模块包含在Python的基本安装包中.使用tkinter模块编写的GUI程序是跨平台的.可在windows.UNIX.Linux以及Macintonsh OS X ...

  2. Python中用类实现对象和封装

    """ 用类实现对象和封装 对象:对应客观世界的事物,将描述事物的一组数据和与这组数据有关的操作封装在一起, 形成一个实体,这个实体就是对象 类:具有相同或相似性质的对象 ...

  3. Ubuntu16.04 安装和卸载MySQL数据库

    Ubuntu16.04 安装和卸载MySQL数据库 1 安装 安装非常简单,只需要三个命令 1.1 安装服务端 sudo apt-get install mysql-server 在这一步过程中会有提 ...

  4. c++对于c的扩展_冒号作用域

    冒号作用域 ::(该运算符为作用域):如果::前面什么都没加代表全局作用域 #include <iostream> using namespace stu; int a=10; viod ...

  5. cannot find module providing package github.com/× working directory is not part of a module

    今天在搭建fabric的过程中遇到一个问题,记录一下 root@zitao /home/hong/Desktop/gowork/src/github.com/hyperledger/fabric re ...

  6. Kubernetes构建云原生架构-图解

  7. Intellij IDEA中查看字节码

    首先安装插件,这俩都勾上 Intellij IDEA 直接集成了一个工具菜单,可以直接查看字节码,打开 ByteCode 插件窗口方法如下:

  8. print,printf,println的区别,以及\r,\n,\r\n的区别

    1.常用的是println,就是换行输出 2.print,不换行输出 3.printf常使用于格式转化 public class Print { public static void main(Str ...

  9. 在Vue3项目中使用pinia代替Vuex进行数据存储

    pinia是一个vue的状态存储库,你可以使用它来存储.共享一些跨组件或者页面的数据,使用起来和vuex非常类似.pina相对Vuex来说,更好的ts支持和代码自动补全功能.本篇随笔介绍pinia的基 ...

  10. Mysql学习day1

    安装了Mysql以及SQLyog,将SQLyog和数据库做了连接. 学习了基础数据类型以及命令行语句 1 alter table `student` rename as `stu``lesson` 2 ...