0

I am new to multi-threading and I stumbled across an error which I was hoping someone could explain to me why was happening.

My initial program code did not have multi-threading and I was populating some charts with data from a datagridview. I was getting values like this:

Val = dgv.Rows(counter).Cells(columnName).Value

Since I was populating four charts using the same grid, I wanted to put this chart population process on multiple threads. I got an error when trying to update GUI elements (such as labels and a progress bar) and stumbled across this thread: .NET Controls: Why aren't all calls thread-safe?

So my fix was to have the main thread update the GUI elements, and the backgroundworkers just report progress to the main thread.

However, I still getting a cross-thread error when trying to read the value using the function above. I'd like to know why this is the case.

I solved my problem using Invoke (which I believe is the correct way of doing it), ie. something like this:

dgv.Invoke(New ReadDGVCallBack(AddressOf ReadDGV), counter, "Name")

where "Name" is the column name.

However, I still am curious to know why I can't read a value from a datagridview from another thread. Since I am not modifying it, shouldn't it be fine if data is just being read? Could someone shed some light on this?

Thanks for all the help

Community
  • 1
  • 1
Aommaster
  • 115
  • 15
  • 1
    You didn't post enough code to make the call. Hard to see how a *counter* value and a "Name" string might have anything to do with the first snippet. Code is not thread-safe when one thread can write a variable and another thread can read it. You claim to only read but you are certainly overlooking the write case. Of course the user can edit the value while your worker thread is running. Nothing ever good happens when he does that. Collect the data your thread needs before you start it. Set the dgv's Enable property to False to make it obvious that editing is not okay. – Hans Passant Apr 05 '14 at 12:04
  • Hi Hans! That's definitely it. The DGV allows the user to modify cells present in two columns (which also happen to be the columns I am reading). I hadn't considered this situation. Edit: I have also modified my initial post accordingly for clarification. Thanks! – Aommaster Apr 05 '14 at 12:24

0 Answers0