c# backgroundworker 无法处理我想要它执行的代码
我的代码在强制执行时不会出现任何错误,我只是在尝试运行它时出现错误。它说 ThreadStateException 不受用户代码的控制,我在多个地方搜索了这个,我的所有代码看起来都以同样的方式工作,我知道问题是什么。这是不起作用的代码,
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);
}
}
}
}
任何帮助将不胜感激
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);
}
}
}
}
any help will be appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在线程中显示表单(对话框)。
另外,请确保处理 Completed 事件并检查
if (e.Error != null) ...
否则你将忽略错误。
You cannot show a Form (Dialog) from withing the Thread.
Also, make sure you handle the Completed event and check
if (e.Error != null) ...
Otherwise you will be ignoring errors.
在 DoWork 方法中添加一些异常处理。
请看这里: http:// /social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/74d91404-9bc8-4f8f-8eab-4265afbcb101/
Add some exception handling into your DoWork method.
Look here: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/74d91404-9bc8-4f8f-8eab-4265afbcb101/