c# backgroundworker won't work with the code I want it to do
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 == 开发者_StackOverflowDateTime.Today.Date)
{
File.Copy(fi.FullName, target.FullName +"\\"+ fi.Name, true);
}
}
}
}
any help will be appreciated
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;
....
}
Also, make sure you handle the Completed event and check if (e.Error != null) ...
Otherwise you will be ignoring errors.
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/
string ErrorMessage = "";
void bgw_DoWork(object sender, DoWorkEventArgs ea)
{
//some variable declarations and initialization
try
{
//do some odbc querying
ErrorMessage = "";
}
catch (Exception ex)
{
//stuff..
ErrorMessage = ex.Message;
}
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null || !string.IsNullOrEmpty(ErrorMessage))
{
//do something
MessageBox.Show(ErrorMessage);
}
else
{
//do something else
}
}
精彩评论