我有一个应用程序将从文本文件从目录读取到数据库中的数据。我有一个用户界面,允许用户点击导入按钮并开始导入数据,当用户再次点击该按钮时,我想停止导入这些文件中的数据。我开始使用线程来允许这样做,以便在导入数据时不会冻结UI。但我有几个问题。我开始使用thread.Abort()在用户停止导入后终止线程,但是当用户再次单击导入时,一些重复数据被添加到数据库,因为它开始读取文本文件的顶部,我不想要。我被告知使用ManualResetEvents和Thread.Join()来触发导入完成,但我很困惑,应该如何工作。现在我的代码如下所示:c#线程与手动重置事件
public ManualResetEvent event1 = new ManualResetEvent(false);
public Thread workerThread;
public Form1
{
InitializeComponent();
}
private void importButton_Click(object sender, EventArgs e)
{
if(importButton.Text == "Begin Import")
{
importButton.Text = "Stop Import";
//runs a service that begins reading and importing data and writing to
//a "console" box.
Service service = new Service(consoleBox);
//run the new thread to begin importing data
workerThread = new Thread(service.importData);
workerThread.Start();
}
else
{
importButton.Text = "Begin Import";
event1.Set();
while(!event1.WaitOne(TimeSpan.FromSeconds(4)))
{ //imports data for 30 more text files
service.importData(30);
workerThread.Join();
}
}
}
基本上什么即时试图做的是保持胎面循环和检查,看看是否有任何文件被读出,如果有再导入数据,否则睡4秒。我应该使用线程计时器吗?我有点不确定要做什么。