C# 다중 스레드가 모든 스레드가 끝날 때까지 기다리는 문제
8075 단어 다중 스레드
using System;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
private static AutoResetEvent[] events;
static void Main(string[] args)
{
int threadNum = 10;
Thread[] thread = new Thread[threadNum];
events = new AutoResetEvent[threadNum];
for (int i = 0; i < threadNum; i++)
{
var waithandler = new AutoResetEvent(false);
events[i] = waithandler;
ThreadStart starter = delegate
{
var param = new Tuple<string, AutoResetEvent>("test print:" + i, waithandler);
Print(param);
};
thread[i] = new Thread(starter)
{
Name = "thread" + i.ToString()
};
}
for (int i = 0; i < threadNum; i++)
{
thread[i].Start();
}
WaitHandle.WaitAll(events);
Console.WriteLine("Completed!");
Console.Read();
}
private static void Print(object param)
{
var p = (Tuple<string, AutoResetEvent>)param;
Console.WriteLine(Thread.CurrentThread.Name + ": Begin!");
Console.WriteLine(Thread.CurrentThread.Name + ": Print" + p.Item1);
Thread.Sleep(300);
Console.WriteLine(Thread.CurrentThread.Name + ": End!");
p.Item2.Set();
}
}
}
한 번에 Set, 사실 ManualResetEvent를 사용하면 충분합니다.
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var waits = new List<EventWaitHandle>();
for (int i = 0; i < 10; i++)
{
var handler = new ManualResetEvent(false);
waits.Add(handler);
new Thread(new ParameterizedThreadStart(Print))
{
Name = "thread" + i.ToString()
}.Start(new Tuple<string, EventWaitHandle>("test print:" + i, handler));
}
WaitHandle.WaitAll(waits.ToArray());
Console.WriteLine("Completed!");
Console.Read();
}
private static void Print(object param)
{
var p = (Tuple<string, EventWaitHandle>)param;
Console.WriteLine(Thread.CurrentThread.Name + ": Begin!");
Console.WriteLine(Thread.CurrentThread.Name + ": Print" + p.Item1);
Thread.Sleep(300);
Console.WriteLine(Thread.CurrentThread.Name + ": End!");
p.Item2.Set();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java 다중 스레드를 순차적으로 실행하는 몇 가지 방법 요약Java 다중 스레드를 순차적으로 실행하는 몇 가지 방법 요약 동료는 무심결에 이 문제를 제기하고 두 가지 방법을 직접 실천했다.물론 더 좋은 방법이 있을 거야. 방법 1 이런 방법은 비교적 흔히 볼 수 있는 해결 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.