Task+ConcurrentQueue,看懂队列和多线程的作用
利用队列+多线程提高程序运行的效率,
直接上代码
static void Main(string[] args)
{
// CreateTextNoTask();
CreateTextHasTask();
}
/// <summary>
/// 没有多线程生成txt
/// </summary>
public static void CreateTextNoTask()
{
DateTime beginTime = DateTime.Now;
Console.WriteLine($"开始时间:{beginTime}");
int count = 10000;//需要生成的txt数量
int i = 1;
int secondSpan = 0;
while (i <= count)
{
using (StreamWriter streamWriter = File.AppendText($@"F:\test\2\txt_{i}_{Guid.NewGuid().ToString()}.txt"))
{
for (int j = 0; j < 1000; j++)
{
streamWriter.WriteLine($@"{DateTime.Now}");
}
}
i++;
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - beginTime; //计算时间差
secondSpan = (int)ts.TotalSeconds; //将时间差转换为秒
Console.WriteLine($"结束时间:{DateTime.Now}");
Console.WriteLine($"耗时:{secondSpan} 秒!");
Console.ReadKey();
}
/// <summary>
/// 利用多线程生成txt
/// </summary>
public static void CreateTextHasTask()
{
DateTime beginTime = DateTime.Now;
Console.WriteLine($"开始时间:{beginTime}");
int secondSpan = 0;
int count = 10000;//需要生成的txt数量
int threadNum = 8; //定义线程数量
int outItem = 0;
ConcurrentQueue<int> queues = new ConcurrentQueue<int>();
for (int q = 1; q <= count; q++)
{
queues.Enqueue(q);
}
List<Task> tasks = new List<Task>();
for (int t = 0; t < threadNum; t++)
{
//Console.WriteLine($"开启一个新线程t={t}");
tasks.Add(new Task(() =>
{
while (true)
{
//业务处理
var isExit = queues.TryDequeue(out outItem);
//Console.WriteLine($"从队列中取出数据:{outItem}");
if (!isExit)
{
//Console.WriteLine($"----------------------队列中没数据啦----------------------");
break;
}
else
{
using (StreamWriter streamWriter = File.AppendText($@"F:\test\2\txt_{outItem}_{Guid.NewGuid().ToString()}.txt"))
{
for (int j = 0; j < 1000; j++)
{
streamWriter.WriteLine($@"{DateTime.Now}");
}
}
//Console.WriteLine($"生成txt");
}
}
}));
}
//Console.WriteLine($"tasks.ForEach(a => a.Start());");
tasks.ForEach(a => a.Start());
//Console.WriteLine($"Task.WaitAll(tasks.ToArray());");
Task.WaitAll(tasks.ToArray());
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - beginTime; //计算时间差
secondSpan = (int)ts.TotalSeconds; //将时间差转换为秒
Console.WriteLine($"结束时间:{DateTime.Now}");
Console.WriteLine($"耗时:{secondSpan} 秒!");
Console.ReadKey();
}

浙公网安备 33010602011771号