C#中的BackgroundWorker不会与code工作,我想要它做的 [英] c# backgroundworker won't work with the code I want it to do
问题描述
我的code引人注目的,当我刚刚得到一个试图运行它带来了没有错误。它说ThreadStateException被用户code我已经在多个地方搜索了这一点,我所有的code相以同样的方式,我有知道的想法是什么问题工作unhanded。这里是code的心不是工作
my code brings up no errors when compelling i just get one while trying to run it. it says ThreadStateException was unhanded by the user code i have searched for this in multiple places and all my code looks to work in the same way i have know idea what the problem is. here is the code that isnt working
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FolderBrowserDialog dlg2 = new FolderBrowserDialog();
if (dlg2.ShowDialog() == DialogResult.OK)
//do whatever with dlg.SelectedPath
{
DirectoryInfo source = new DirectoryInfo(dlg.SelectedPath);
DirectoryInfo target = new DirectoryInfo(dlg2.SelectedPath);
DirectoryInfo dir = new DirectoryInfo(dlg.SelectedPath);
FileInfo[] fis = dir.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo fi in fis)
{
if (fi.LastWriteTime.Date == DateTime.Today.Date)
{
File.Copy(fi.FullName, target.FullName +"\\"+ fi.Name, true);
}
}
}
}
任何帮助将AP preciated
any help will be appreciated
推荐答案
您不能从withing线程显示表(对话)。
You cannot show a Form (Dialog) from withing the Thread.
private void button1_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dlg2 = new FolderBrowserDialog())
{
if (dlg2.ShowDialog() == DialogResult.OK)
{
backgroundWorker1.RunWorkerAsync(dlg2SelectedPath);
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string selectedpath = (string) e.Args;
....
}
此外,请确保您处理完成的事件,并检查如果(e.Error!= NULL)...
结果
否则,你会忽略的错误。
Also, make sure you handle the Completed event and check if (e.Error != null) ...
Otherwise you will be ignoring errors.
这篇关于C#中的BackgroundWorker不会与code工作,我想要它做的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!