소스 코드:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
static ConcurrentDictionary<int,int> a = new ConcurrentDictionary<int, int>();
static void Main(string[] args)
{
new Thread(f) { IsBackground = true}.Start();
Thread.Sleep(100);
foreach(var x in a)
{
Thread.Sleep(1);
Console.WriteLine(x);
}
}
static void f()
{
for(int i = 0; ;i++)
{
a[i] = i;
Console.WriteLine("set:" + i);
Thread.Sleep(1);
}
}
}
}
ConcurrentDictionary를 Dictionary로 바꾸면 컬렉션이 수정 어쩌고 열거 작업이 저쩌고 라는 오류가 나온다. 다른 스레드에서 a를 수정했기 때문이다.
출력 결과:
set:0
set:1
set:2
set:3
set:4
set:5
set:6
set:7
set:8
set:9
[0, 0]
[1, 1]
set:10
[2, 2]
set:11
[3, 3]
set:12
[4, 4]
set:13
[5, 5]
set:14
[6, 6]
set:15
[7, 7]
set:16
[8, 8]
set:17
[9, 9]
set:18
[10, 10]
set:19
[11, 11]
set:20
set:21
[12, 12]
[13, 13]
set:22
set:23
[14, 14]
set:24
[15, 15]
set:25
[16, 16]
계속하려면 아무 키나 누르십시오 . . .
결론: 오류가 나지 않는다.
'C#' 카테고리의 다른 글
[C#] 서버 시간 가져오기 (0) | 2023.10.18 |
---|---|
lock (1) | 2023.07.02 |
파일 읽고 쓰기의 비효율성 (0) | 2023.05.27 |
class vs struct (0) | 2023.05.18 |
[C# Windows] System.IO.Path.GetTempPath 쓰지 마라. (0) | 2023.05.09 |
댓글