[c#] task를 이용한 간단한 멀티스레드 예제
닷넷 환경에서 c#으로 멀티스레드를 구현하려면 task parallel library를 쓰는 게 제일 좋다. task를 이용하는 가장 좋은 방법은 TaskFactory.StartNew나 TaskFactory<TResult>.StartNew 메서드를 쓰는 거다. Task.Run이 더 간단하지만 이건 아규먼트를 넘길 수 없다.
아래 예제는 클래스 하나를 바인딩 리스트에 담은 뒤 새로 스레드를 만들어 여기에서 바인딩 리스트의 아이템을 바꾸는 거다.
class Class1
{
public int Int { get; set; }
}
BindingList<Class1> Class1s = new();
private void Form1_Load(object sender, EventArgs e)
{
Class1 class1 = new();
class1.Int = 1;
Class1s.Add(class1);
dataGridView1.DataSource = Class1s;
}
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(task, 2);
void task(object? object1)
{
Class1 class1 = new();
class1.Int = (int)object1!;
Class1s[0] = class1;
}
}
In .NET Framework 4, the TPL is the preferred way to write multithreaded and parallel code.
– Task Parallel Library (TPL)
An alternative, and the most common way to start a task in the .NET Framework 4, is to call the static TaskFactory.StartNew or TaskFactory<TResult>.StartNew method.
– Task<TResult> Class