标签:space 调用 console fun new OLE lse vat UNC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp7
{
public class TaskManage
{
public int maxcount;
public int countnum = 0;
public TaskManage(int worknum)
{
maxcount = worknum;
}
public void Run(Action< object> func, object s)
{
while (countnum >= maxcount)
{
Thread.Sleep(5);
}
lock (this)
{
countnum++;
}
Task task = new Task(() =>
{
func(s);
lock (this)
{
countnum--;
}
});
task.Start();
}
public void WaitComplete()
{
while (countnum > 0)
{
Console.WriteLine("***************"+countnum);
Thread.Sleep(5);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApp7
{
public class WorkBackground
{
public delegate void BackgroundMethod(params object[] objs);
private int threadCount = 0;
private int MaxThreadCount = 0;
public WorkBackground(int maxThreadCount)
{
MaxThreadCount = maxThreadCount;
}
public void Run(BackgroundMethod backgroundMethod, params object[] objs)
{
while (threadCount >= MaxThreadCount)
{ Thread.Sleep(5); }
lock (this) { threadCount++; }
Thread thread = new Thread((object threadObj) =>
{
if (threadObj as object[] != null)
{ backgroundMethod(threadObj as object[]); }
else
{ backgroundMethod(); }
lock (this) { threadCount--; }
});
thread.IsBackground = true;
thread.Start(objs);
}
public void WaitComplete()
{
while (threadCount > 0)
{ Thread.Sleep(5); }
}
}
}
调用
//第一种
//TaskManage taskManage = new TaskManage(5);
//for (int i = 0; i < 10000; i++)
//{
// taskManage.Run(delegate (object[] s)
// {
// Console.WriteLine("s:" + s);
// }, i);
//}
//taskManage.WaitComplete();
//Console.ReadKey();
//第二种
WorkBackground taskManage = new WorkBackground(5);
for (int i = 0; i < 10000; i++)
{
taskManage.Run(delegate (object[] s)
{
Console.WriteLine("s:" + s[0]);
}, i);
}
taskManage.WaitComplete();
Console.ReadKey();
标签:space 调用 console fun new OLE lse vat UNC
原文地址:https://www.cnblogs.com/wlzhang/p/10337654.html