For a project I am working on I have a form with a bunch of DataGridView components that are to display some data. Every DataGridView has it's own DataTable associated it. The data that is to be displayed is send periodically. My application has to read this data, parse it and fill the datagrids accordingly. Because I want to maintain responsiveness of the form I implemented the receiving of data (blocking) in an endless background worker.

In the background worker I obtain the data and parse/convert it into values that fit in the DataTables. Now here is my question: At the moment I assign these values directly to the DataTable objects. (So I do this from within the backgroundworker's DoWork event)

I am wondering if this is valid. I did have an index out of bounds exception once and I was wondering if this was somehow associated with this. Is this a safe and recommended way of doing it, or should I use invokes in my backgroundworker's DoWork event to update the DataTables?

有帮助吗?

解决方案

No, all properties on .NET WinForm controls (this is the assumption) that affect the rendering of the control (including values bound to the control which would affect the rendering) must be made on the thread that created the control.

That said, there are many times when you will get away with being able to make the changes, but the behavior is unpredictable and not recommended.

In your specific case, I'd suggest having a copy of the DataTable that the processing thread works with, and then marshal that copy to the UI thread (through a call to one of the ISynchronizeInvoke interface implementation, which the Control class implements) and update the grid in the UI thread.

Basically, you'd perform an update of the DataTable that the grid is bound to with the copy marshaled from the background thread.

其他提示

It's fair to say that you should never update any UI bound elements from a non-ui thread. Although very often you may not see any exception if you do so, it never good practice, and often leads to exceptions or worse still, unseen errors

Well, no. Though it is a very good idea to do calculation in a background thread, UI update should be done in UI thread, always.

When binding Datatable to UI element, you "give" ownership on these objects to the UI thread and should no longer update them in background threads

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top