views:

136

answers:

1

I have a Form that uses a BackgroundWorker to execute a series of tests. I use the ProgressChanged event to send messages to the main thread, which then does all of the updates on the UI. I've combed through my code to make sure I'm not doing anything to the UI in the background worker. There are no while loops in my code and the BackgroundWorker has a finite execution time (measured in seconds or minutes). However, for some reason when I lock my computer, often times the application will be hung when I log back in. The thing is, the BackgroundWorker isn't even running when this happens. The reason I believe it is related to the BackgroundWorker though is because the form only hangs when the BackgroundWorker has been executed since the application was loaded (it only runs when given a certain user input).

I pass this thread a List of TreeNodes from a TreeView in my UI through the RunWorkerAsync method, but I only read those nodes in the worker thread..any modifications I make to them is done in the UI thread through the progressChanged event.

I do use Thread.Sleep in my worker thread to execute tests at timed intervals (which involves sending messages over a TCP socket, which was not created in the worker thread).

I am completely perplexed as to why my application might be hanging. I'm sure I'm doing something 'illegal' somewhere, I just don't know what.

A: 

I pass this thread a List of TreeNodes from a TreeView in my UI through the RunWorkerAsync method, but I only read those nodes in the worker thread.

By "only read" I assume you mean "only access property getters". But property getters can execute code that you don't control - for example TreeNode.IsSelected will call a native method and send a Windows message (take a look with Reflector).

Instead you should extract the data you need from the TreeView in the UI thread and pass it to the background worker. Not only will you avoid this problem, but your design will be more loosely coupled.

Joe
I have extended the TreeNode class to add a bunch of data to the nodes that I need to use..it would be a lot of work to extract this data into data structures and pass it along. What if I just passed the TreeNodes to the BGW, and then in the BGW I created copies of each node before accessing any of their data?
alexD
I'd say bite the bullet. Accessing UI elements from a backgroundworker results in undefined behavior. Even if you somehow get it working, it will be a maintenance nightmare.
Joe
What if I only access my own attributes of the class where I know there aren't any special invocations going on? IF I need the 'IsChecked' property, I could just create my own and set it before handing it off to the BGW.
alexD