我有一个使用C#的WinForms应用程序。我尝试从文件中读取一些数据并将其插入到数据表中。在此操作繁忙时,我的表单冻结,无法进行事件移动。有谁知道我该如何解决这个问题?
最佳答案
这可能是因为您在UI线程上执行了该操作。
将文件和数据库操作移至另一个线程,以防止UI线程冻结。
这是使用ThreadPool的示例。
作为替代方案,您可以手动启动线程,但是如果需要,则需要手动跟踪它们。想中止他们等等。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// With ThreadPool
ThreadPool.QueueUserWorkItem(DoWork);
}
private void DoWork(object state)
{
// Do Expensive Work
for (int i = 0; i < 100; i++)
{
Thread.Sleep(10);
}
System.Diagnostics.Debug.WriteLine("DoWork finished!");
}
}
}