Passing A Datatable to Another Thread

G

Guest

One of my routines is running queries, with some of them taking several minutes. I would like the filling of the table to take place in a different thread and then just pass me the resultant table.

I can access the data just fine, but when I try to use the tables as a datasource there is an exception: "Controls created on one thread cannot be parented to a control on a different thread."

First, I tried creating the table outside the thread and then just filling it inside the thread. That didn't work, so then I tried cloning the table and then recreating all of the rows (which I don't want to do because sometimes the table has several hundred thousand rows). But that didn't work either.

What is the problem and how can I get around it (if possible, without recreating the whole table)?
 
R

Richard Myers

The problem is not with the datatable, it is with the control to which you
are attempting to assign the Datatable as a datasource.

The controls in your UI have been parented to the UI thread of the Windows
form... not the thread you spin up to grab your data. So when you try to use
your data thread to access the controls parented by the UI thread that when
the error occurs.

Everyone makes this mistake when learning to use threads.

You solution is to either d an Async Call back, which is alot easier than it
sounds or simply use the

mycontrol.BeginInvoke mechanism to access the control parented on the UI
thread.
You can use the

You can also use Control.InvokeRequired as a conditional to determine
whether you need to call an invoke on any given control.

hth
Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top