The code that I’m working on at the moment had a method that ran in the UI thread. But it was taking a long time, so I decided to put it in a BackgroundWorker. The code was normally editing the UI and when I changed the thread there came the problem of editing the controls in the UI thread. So what I did was to make the method report it’s state, and change the UI in ProgressChanged event. To report the progress, this method takes one object named “userState”, but for my purposes, I had to report more than one object. So I chose to do the following:
// Create a dictionary to keep method state for reporting.
// "state" item represents a state type; "error", "update", "success".
// "message"d item represents the message associated with the state.
// "result" item represents the function result.
// "invisiblecolumns" item represents the invisible columns this method finds.
var methodState = new Dictionary<string, object> { { "state", "update" }, { "message", string.Empty },
{ "result", null }, { "invisiblecolumns", null } };
But I’m not sure if this is a good way to do it. What would your suggestion be as to how to handle the reporting process in a background worker? What is a good practice? And is what I did a good workaround?
I think it’s better to create a class for your operation result (also I’d give this class more descriptive name, thus you are performing some specific operation):
Your code will be much more readable, maintainable, and you’ll have IntellySense support. Compare:
With