form1中的代码是这样的:
[C#] 纯文本查看 复制代码 private void button2_Click(object sender, EventArgs e)
{
Scan s=new Scan(this);
s.RunTask();
}
Scan类中的代码是这样的:
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsApp1
{
public class Scan
{
private Form1 frm;
/// <summary>
/// 线程最大总数
/// </summary>
private int thread_num = 20;
public Scan(Form1 form,int threadNum=20)
{
this.frm = form;
this.thread_num = threadNum;
}
public void RunTask()
{
#region 初始化数据
int[][] dirsArray = new int[100][];
for (int i = 0; i < 100; i++)
{
int[] innerArray = new int[i];
for (int j = 0; j < i; j++)
{
innerArray[j] = i;
}
dirsArray[i] = innerArray;
}
#endregion
Task.Run(() =>
{
Debug.WriteLine($"当前线程CurrentThreadId={Thread.CurrentThread.ManagedThreadId}");
//1.从数据库中获取数据
//设置线程数
if (dirsArray.Length<this.thread_num)
{
this.thread_num = dirsArray.Length;
}
ParallelOptions parallelOptions = new ParallelOptions()
{
MaxDegreeOfParallelism = this.thread_num
};
ParallelLoopResult result = Parallel.ForEach(dirsArray, parallelOptions, currentTypeArray =>
{
Debug.WriteLine($"CurrentThreadId={Thread.CurrentThread.ManagedThreadId},执行{string.Join(", ", currentTypeArray)}");
//this.frm.Func(string.Join(", ", currentTypeArray));
foreach (var num in currentTypeArray)
{
Thread.Sleep(1);
}
});
while (result.IsCompleted)
{
Console.WriteLine("是否完成:{0}", result.IsCompleted);
Console.WriteLine("最低迭代:{0}", result.LowestBreakIteration);
break;
}
});
Console.WriteLine("数据跑完啦!");
}
}
}
但执行的结果却不显示执行完的情况:
当执行完所有的线程后,并没有出现:
true
数据跑完啦!
等预想的输出结果,这是怎么回事啊?请大神帮忙解决下,谢谢!
|