Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

C# WindowsForms MultiThreaing - Question

$
0
0
Hello all

This is my first post here at Dream.In.Code, I hope that I am complying with the rules with this post :)/>/>/>/>/>

I've been working on a simple Windows Forms application that copies files/folders from A to B. I picked a Form application because I want to see the which files were being copied along with a shiny progress bar.

The first problem I ran into was having the form run on a single thread - the form would crash / stop responding because it was trying to do too much at once. So I looked into running the file copying section of my code on another thread - freeing up the resources for the form. Here's what I came up with:

private delegate void CopyFilesDelegate( string source, string dest, bool subdirs, ProgressBar pb, ListBox lb1, ListBox lb2); // Delegate for Copy Files method

//CopyFiles Method
private static void CopyFiles( string source, string dest, bool subdirs, ProgressBar pb, ListBox lb1, ListBox lb2)
{
   //Do some Dir / File exists checking
   //Copy File
   //Add file name to a ListBox when copied
   //etc
}

//Button1 Click handler
private void button1_Click(object sender, EventArgs e)
{
     Thread Worker = new Thread(CopyWorker);
     Worker.IsBackground = true;
     Worker.Start();
}
//CopyWorker Method
public void CopyWorker()
{
     CopyFilesDelegate handler = new CopyFilesDelegate(CopyFiles);
     handler(source, dest, true, progressBar3, listBox1, listBox2);
}



Now running the application with this thread setup works perfectly - no freezing / crashing. However if I run in Debug mode that debugger stops as soon as it gets to an object and throws a InvalidOperationExecption - Cross threaded operation not valid: 'listbox1' access from a thread other than the thread it was created on.

So I checked out the help link and followed the examples on thread safe calls and modified my "CopyWorker" method to the following:

   
public void CopyWorker()
{
     CopyFilesDelegate handler = new CopyFilesDelegate(CopyFiles);
     Invoke(handler, new Object[] { source,  dest, true,  progressBar3,  listBox1,  listBox2});
}


This declaration stops the debugger from throwing exceptions, however the form freezes / locks up when executing.

Now :)/>/> here is my question, why does the unsafe version run as intended where as the 'safe' version seems to act as tho it's not using its own thread?

I'm sure the answer is simple (at least I hope it is lol) but I'm just not understanding both concepts correctly, so I'm reaching out to the community for help :)/>/>

I'd really appreciate any advice that can be given. being a 'developing' programmer I may have bitten off more than I can chew.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>