【发布时间】:2016-07-21 12:27:16
【问题描述】:
我正在开发 Windows Form C# 程序,它每 20 分钟从共享驱动器中读取 Excel 数据(我使用的是“计时器”)- 功能“插入”。由于性能,我想一次读取多个 Excel 文件。出于这个原因,我正在使用线程。
每个线程都调用一个函数 (LoadExcelData),该函数将数据从 Excel 读取到 ArrayList。我想知道所有线程何时完成(当所有 excel 文件都加载到 ArrayList 时),以便将此 ArrayList 插入内部数据库。
我尝试使用 thread[i].Join() 但这会冻结 GUI。我也不知道如果我有 100 多个文件并且因此有 100 多个线程会发生什么。这会导致内存异常或其他异常吗?
//Execute every 20 minutes (Timer). Do not Execute in case previouse run is not finished
void inserting(List<String> excels){
int numOfThreads=excels.length;
Thread[] threads = new Thread[numOfThreads];
for (int index = 0; index < numOfThreads; index++)
{
int i = index;
threads[index] = new Thread(() =>
{
LoadExcelData(excels[i].File_name); //function loads excel data to global array "Weather" which is used later on
});
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Start(); //start thread
}
for (int i = 0; i < threads.Length; i++)
{
// threads[i].Join(); //this freezes GUI!
}
InsertToDB(object of ArrayList<ClassName>); //insert data which was read from Excels
isRunning=false;//Data was successefully inserted to DB
}
我想每 20 分钟运行一次。我正在使用计时器:
timer = new System.Windows.Forms.Timer();
timer.Tick += new EventHandler(timerEventHanlder);
timer.Interval = 20 * 60000; // in miliseconds
timer.Start();
private void timerEventHanlder(object sender, EventArgs e)
{
List<String> excels = getExcels();
if (!isRunning){ //in case previous timer even is not finished wait another 20 minutes...
isRunning=true; //flag to true
inserting(excels);
}
}
有没有更好的等待来解决上述问题?
【问题讨论】:
-
就我个人而言,出于性能考虑,我几乎从不使用线程。我几乎总是使用它们来保持 UI 响应。实际上,我确实认为线程会降低性能,因为跨线程通信过度和锁定/同步。
-
从一开始我就为同样的事情做这件事 - GUI 冻结了。但是后来我需要知道由于计时器的原因所有线程何时完成,并且我使用了导致 GUI 再次冻结的 thread.Join() 事件。在我的情况下,性能得到了提高,因为两个(或更多)Excel 文件的处理速度更快。
标签: c# multithreading winforms timer threadpool