threadpool 을 이용한 처리 (64개이상 처리를 위해 수정됨)
// program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadPoolTest
{
class Program
{
static void Main(string[] args)
{
PoolWorker poolWorker = new PoolWorker();
poolWorker.DoWork();
}
}
}
// poolworker.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadPoolTest
{
// 메인워커가 일 끝내고 나서 처리할 함수를 위한 deletegate
public delegate void ThreadCallBackMethod(string parameter1);
class PoolWorker
{
public void DoWork()
{
int setMinTrheads = 1;
int setMaxThreads = 6;
int doWorkCnt = 100;
ThreadPool.SetMinThreads(setMinTrheads, setMinTrheads);
ThreadPool.SetMaxThreads(setMaxThreads, setMaxThreads);
List<ManualResetEvent> manualResetEvents = new List<ManualResetEvent>();
for (int i = 0; i < doWorkCnt; i++)
{
ThreadPoolStatus threadPoolStatus = new ThreadPoolStatus();
threadPoolStatus.signal = new ManualResetEvent(false);
manualResetEvents.Add(threadPoolStatus.signal);
MainWorker mainWorker = new MainWorker(i, ThreadCompletedAndExecuteMethod);
ThreadPool.QueueUserWorkItem(mainWorker.DoWork, threadPoolStatus);
}
WaitForAll(manualResetEvents);
}
//각각의 메인워커들이 실행을 끝내고 수행할 함수
public static void ThreadCompletedAndExecuteMethod(string msg)
{
Console.WriteLine("ThreadCallback Excuted..{0}", msg);
}
static void WaitForAll(List<ManualResetEvent> manualResetEvents)
{
if (manualResetEvents == null) return;
foreach (ManualResetEvent t in manualResetEvents)
{
// 신호 받을때까지 메인을 차단하는 역할
t.WaitOne();
}
}
}
public class ThreadPoolStatus
{
public ManualResetEvent signal;
}
}
// mainworker.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadPoolTest
{
class MainWorker
{
int parameter;
ThreadCallBackMethod callbackMethodName;
public MainWorker(int parameter, ThreadCallBackMethod methodName)
{
this.parameter = parameter;
this.callbackMethodName = methodName;
}
public void DoWork(object theadPoolStatus)
{
ThreadPoolStatus status = theadPoolStatus as ThreadPoolStatus;
if (status == null) return;
Thread.Sleep(500);
Console.WriteLine(parameter);
callbackMethodName(this.parameter.ToString());
status.signal.Set();
}
}
}