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 不能使用我想要的代码


基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30