c# backgroundworker won#39;t work with the code I want it to do(c# backgroundworker 不能使用我想要的代码)
问题描述
我的代码在强制执行时不会出现错误,我只是在尝试运行它时得到一个.它说 ThreadStateException 没有被我在多个地方搜索过的用户代码处理,我所有的代码看起来都以同样的方式工作,我知道问题出在哪里.这是不工作的代码
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);
}
}
}
}
任何帮助将不胜感激
推荐答案
你不能通过线程显示表单(对话框).
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;
....
}
另外,请确保您处理 Completed 事件并检查 if (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 不能使用我想要的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c# backgroundworker 不能使用我想要的代码
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
