程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#限制並發線程數例程

C#限制並發線程數例程

編輯:關於C#

按自己的想法實現的C#版本的限制並發線程數的例程,給有需要的讀者

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace WZDM.Test
{
/// <summary>
/// 限制並發線程數例程
/// </summary>
public class TestThread
{
int _currentThreads = 0;
int _maxThreads = 10;

public void Test()
{
while (true)
{
//_maxThreads = new Random().Next(1, 10);
for (int i=0; i<100; i++)
{
// 在此進行數量限制
if (_currentThreads >= _maxThreads)
break;

// 開啟線程
lock (typeof(TestThread))
{
_currentThreads++;
if (_currentThreads > _maxThreads)
_currentThreads = _maxThreads;

string currentInfo = string.Format("thread {0}/{1}", _currentThreads, _maxThreads);
Console.WriteLine(currentInfo + " start");
Thread thread = new Thread(new ParameterizedThreadStart(Run));
thread.Start(currentInfo);
}
}

System.Threading.Thread.Sleep(2000);
}
}

// 線程任務
void Run(object obj)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine("{0}:{1}", obj, i);
Thread.Sleep(100);
}
Console.WriteLine("{0} finished", obj);

lock (typeof(TestThread))
{
_currentThreads--;
if (_currentThreads < 0)
_currentThreads = 0;
}
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved