473,725 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing Objects Into Worker Thread Function

I am using VS2005 for a windows forms application. I need to be able to
use a worker thread function to offload some processing from the UI
thread. The worker thread will need access to a datagridview on the
form. I am using the following code to spawn the worker thread...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction));
WorkerThread.Is Background = true;
WorkerThread.St art();

The problem I am having is...I cannot seem to figure out how to pass
objects into the worker thread function. For example, when I try to
use the following code...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction(ref
dgvMyDataGridVi ew)));
WorkerThread.Is Background = true;
WorkerThread.St art();

....I get the compile time error: "Method name expected".

What am I doing wrong, and how can I make this work?

JP

Jul 24 '06 #1
14 6887
OK; ThreadStart does not accept parameters; in 2.0 there is
ParameterizedTh readStart, but in terms of bang-for-buck, actually captured
variables in an anonymous delegate can be more convenient, plus it is
type-safe:

Thread workerThread = new Thread((ThreadS tart) delegate {
SomeFunction(so meValue); // you need to define SomeFunction
});

Here "someValue" (which could be your gridview) will be "captured" (actually
moved into a seprate class instance); everything inside the braces is
actually the outer function that will be invoked on the new thread, and is
*not* evaluated as part of the assignment to workerThread. Note that
SomeFunction can be strongly typed to accept a datagridview, rather than an
object (which is what ParameterizedTh readStart takes).

However: a bigger problem here is thread affinity. You say you need access
to datagridview - well bad news. You probably can't do much with it, as you
will get illegal thread exceptions unless you do a lot of switching between
threads (via Control.Invoke / Control.BeginIn voke). You may need to do the
processing on the background thread, and then merge the results in a single
block back on the UI thread to maintain performance.

Marc

<jo*********@to pscene.comwrote in message
news:11******** **************@ s13g2000cwa.goo glegroups.com.. .
>I am using VS2005 for a windows forms application. I need to be able to
use a worker thread function to offload some processing from the UI
thread. The worker thread will need access to a datagridview on the
form. I am using the following code to spawn the worker thread...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction));
WorkerThread.Is Background = true;
WorkerThread.St art();

The problem I am having is...I cannot seem to figure out how to pass
objects into the worker thread function. For example, when I try to
use the following code...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction(ref
dgvMyDataGridVi ew)));
WorkerThread.Is Background = true;
WorkerThread.St art();

...I get the compile time error: "Method name expected".

What am I doing wrong, and how can I make this work?

JP

Jul 24 '06 #2
You should not access control data from anything other than the thread that
created the control. In VS2005, I suggest using the BackgroundWorke r class
and have the form/control subscribe to the ProgressChanged event (if you're
not doing an atomic operation that only has a "return") or the
RunWorkerComple ted event. This class ensures that the ProgressChanged event
handler and the RunWorkerComple ted event handler are called on the thread
that created the BackgroundWorke r object (which means you have to create it
on the thread that created the control in order for it to work properly).
Assuming the simplest case, you can do whatever you want to the control/form
in the RunWorkerComple ted event handler. If your handler is not static the
"this" keyword can be used to access the form/control and it's properties and
there is no need to "pass" it into the thread.

--
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"jo*********@to pscene.com" wrote:
I am using VS2005 for a windows forms application. I need to be able to
use a worker thread function to offload some processing from the UI
thread. The worker thread will need access to a datagridview on the
form. I am using the following code to spawn the worker thread...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction));
WorkerThread.Is Background = true;
WorkerThread.St art();

The problem I am having is...I cannot seem to figure out how to pass
objects into the worker thread function. For example, when I try to
use the following code...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction(ref
dgvMyDataGridVi ew)));
WorkerThread.Is Background = true;
WorkerThread.St art();

....I get the compile time error: "Method name expected".

What am I doing wrong, and how can I make this work?

JP

Jul 24 '06 #3
Joey,
..NET 2.0 offers the ParameterizedTh readStart delegate:

http://msdn2.microsoft.com/en-us/lib...readstart.aspx

Otherwise, regarding UI etc. Peter Ritchie's comment would apply.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"jo*********@to pscene.com" wrote:
I am using VS2005 for a windows forms application. I need to be able to
use a worker thread function to offload some processing from the UI
thread. The worker thread will need access to a datagridview on the
form. I am using the following code to spawn the worker thread...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction));
WorkerThread.Is Background = true;
WorkerThread.St art();

The problem I am having is...I cannot seem to figure out how to pass
objects into the worker thread function. For example, when I try to
use the following code...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction(ref
dgvMyDataGridVi ew)));
WorkerThread.Is Background = true;
WorkerThread.St art();

....I get the compile time error: "Method name expected".

What am I doing wrong, and how can I make this work?

JP

Jul 24 '06 #4
Okay, then. What about passing the DataGridView by value, returning it,
and then copying the returned grid over the original one. Does that
sound too crazy? I am looking for a simple way to do it.

If I use the "capture" above and do not indicate "ref", it will pass by
value, right?

Marc Gravell wrote:
OK; ThreadStart does not accept parameters; in 2.0 there is
ParameterizedTh readStart, but in terms of bang-for-buck, actually captured
variables in an anonymous delegate can be more convenient, plus it is
type-safe:

Thread workerThread = new Thread((ThreadS tart) delegate {
SomeFunction(so meValue); // you need to define SomeFunction
});

Here "someValue" (which could be your gridview) will be "captured" (actually
moved into a seprate class instance); everything inside the braces is
actually the outer function that will be invoked on the new thread, and is
*not* evaluated as part of the assignment to workerThread. Note that
SomeFunction can be strongly typed to accept a datagridview, rather than an
object (which is what ParameterizedTh readStart takes).

However: a bigger problem here is thread affinity. You say you need access
to datagridview - well bad news. You probably can't do much with it, as you
will get illegal thread exceptions unless you do a lot of switching between
threads (via Control.Invoke / Control.BeginIn voke). You may need to do the
processing on the background thread, and then merge the results in a single
block back on the UI thread to maintain performance.

Marc

<jo*********@to pscene.comwrote in message
news:11******** **************@ s13g2000cwa.goo glegroups.com.. .
I am using VS2005 for a windows forms application. I need to be able to
use a worker thread function to offload some processing from the UI
thread. The worker thread will need access to a datagridview on the
form. I am using the following code to spawn the worker thread...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction));
WorkerThread.Is Background = true;
WorkerThread.St art();

The problem I am having is...I cannot seem to figure out how to pass
objects into the worker thread function. For example, when I try to
use the following code...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction(ref
dgvMyDataGridVi ew)));
WorkerThread.Is Background = true;
WorkerThread.St art();

...I get the compile time error: "Method name expected".

What am I doing wrong, and how can I make this work?

JP
Jul 24 '06 #5
I am looking for a simple way to do it.
What is the "it" that you are trying to do? "ref" is often used incorrectly
on the assumption that it is necessary to update the *contents* of an
object. It isn't. It is only necessary to reassign the *instance* of an
object. However, in either case I think I must repeat: you really, really
need to be careful of thread-affinity. It is going to bite you. Hard. As
soon as you try to pass a UI control to a different thread you are in a
world of pain. I'm just trying to save you a little frustration...

For completeness: in the more general case, from my example you can simply
define SomeFunction as accepting its parameter with the "ref" keyword, and
use "ref" in the anonymous delegate [i.e. "SomeFunction(r ef someValue);"] -
this will allow someValue to be reassigned inside of SomeFunction. It really
isn't going to work with controls, though. For one thing, the "this.mygri d"
on your form is just a field; the form, however, only cares about the
instance inside "this.Controls" , so *even if you fixed the thread-affinity
gotcha*, you would (if not careful) end up with a different grid on the
(visible) form (this.Controls) , and in the backing "this.mygri d" field.

Personally, I doubt you really need "ref" here; try living without it and
see if it breaks ;-p

Marc
Jul 24 '06 #6
The whole problem here is, when I do a drag/drop on the grid, the
amount of processing (checking cell values, changing their background
colors and read-only properties, etc...) that has to occur can take
some time. Obviously I do not want the user to be staring at a "white"
datagridview that has failed to update itself. And so, I just need to
find a way to do all of this processing on a different thread. There
must be some way to make it work. Should I code a bunch of delegate
functions to change the grid background colors and read-only
properties, etc... and then use Invoke for each to call to the original
UI thread? That is not going to be fun!

What would you guys do with this?
Marc Gravell wrote:
I am looking for a simple way to do it.
What is the "it" that you are trying to do? "ref" is often used incorrectly
on the assumption that it is necessary to update the *contents* of an
object. It isn't. It is only necessary to reassign the *instance* of an
object. However, in either case I think I must repeat: you really, really
need to be careful of thread-affinity. It is going to bite you. Hard. As
soon as you try to pass a UI control to a different thread you are in a
world of pain. I'm just trying to save you a little frustration...

For completeness: in the more general case, from my example you can simply
define SomeFunction as accepting its parameter with the "ref" keyword, and
use "ref" in the anonymous delegate [i.e. "SomeFunction(r ef someValue);"] -
this will allow someValue to be reassigned inside of SomeFunction. It really
isn't going to work with controls, though. For one thing, the "this.mygri d"
on your form is just a field; the form, however, only cares about the
instance inside "this.Controls" , so *even if you fixed the thread-affinity
gotcha*, you would (if not careful) end up with a different grid on the
(visible) form (this.Controls) , and in the backing "this.mygri d" field.

Personally, I doubt you really need "ref" here; try living without it and
see if it breaks ;-p

Marc
Jul 24 '06 #7
What about putting this in the worker thread function...

private void SomeFunctionOnU IThread()
{
Thread WorkerThread = new Thread(new
ThreadStart(Wor kerThreadFuncti on));
WorkerThread.Is Background = true;
WorkerThread.St art();
}

private void WorkerThreadFun ction()
{
DataGridView dgv = (DataGridView)I nvoke(new
GetDataGridView Delegate(this.G etDataGridView) );

//Process any "foreach", etc. on dgv. Any *changes* to be made via
Invoke calls back to UI thread
}

private DataGridView GetDataGridView () //this function is also
on UI thread
{
return(this.dgv MyDataGridView) ;
}

I have used technique this a couple of times before with a treeview,
but never with a datagrid view. The processing here is much more
intensive. I have never seen any warnings/failures about cross-thread
calls with this style before. What do you guys think?

jo*********@top scene.com wrote:
The whole problem here is, when I do a drag/drop on the grid, the
amount of processing (checking cell values, changing their background
colors and read-only properties, etc...) that has to occur can take
some time. Obviously I do not want the user to be staring at a "white"
datagridview that has failed to update itself. And so, I just need to
find a way to do all of this processing on a different thread. There
must be some way to make it work. Should I code a bunch of delegate
functions to change the grid background colors and read-only
properties, etc... and then use Invoke for each to call to the original
UI thread? That is not going to be fun!

What would you guys do with this?
Marc Gravell wrote:
I am looking for a simple way to do it.
What is the "it" that you are trying to do? "ref" is often used incorrectly
on the assumption that it is necessary to update the *contents* of an
object. It isn't. It is only necessary to reassign the *instance* of an
object. However, in either case I think I must repeat: you really, really
need to be careful of thread-affinity. It is going to bite you. Hard. As
soon as you try to pass a UI control to a different thread you are in a
world of pain. I'm just trying to save you a little frustration...

For completeness: in the more general case, from my example you can simply
define SomeFunction as accepting its parameter with the "ref" keyword, and
use "ref" in the anonymous delegate [i.e. "SomeFunction(r ef someValue);"] -
this will allow someValue to be reassigned inside of SomeFunction. It really
isn't going to work with controls, though. For one thing, the "this.mygri d"
on your form is just a field; the form, however, only cares about the
instance inside "this.Controls" , so *even if you fixed the thread-affinity
gotcha*, you would (if not careful) end up with a different grid on the
(visible) form (this.Controls) , and in the backing "this.mygri d" field.

Personally, I doubt you really need "ref" here; try living without it and
see if it breaks ;-p

Marc
Jul 24 '06 #8
I would love to figure out how to do the processing on the background
thread. Trouble is, all of the "processing " involves iterating over the
contents of the datagridview rows.

I can plant plenty of code in the worker thread that will change the
various things in the rows via Invoke calls to the UI thread, but a
real problem is how do I get to where I can actually iterate over them
on the worker thread (foreach, etc...) - that is necessary. The way I
see it, the iteration must be done on the UI thread, period. If that is
so then I will never get rid of my screen-not-updating problem.

I have tried creating a List<DataGridVi ewRow>, and I have also tried
creating a "DataGridViewRo w[] Rowz;" and then using
dgvMyDataGridVi ew.Rows.CopyTo( Rowz). But when they get passed into the
worker thread and are evaluated, cross-thread exceptions are thrown,
just the same. It looks to me like I "copied" the rows, but at runtime
its like I tried to pass the actual rows???

There must be some way to tackle this. What would you do if you had a
datagridview with LOTS of processing that needed to be done, and all of
the processing involved iterating over the rows? Does anyone have an
idea?
Marc Gravell wrote:
OK; ThreadStart does not accept parameters; in 2.0 there is
ParameterizedTh readStart, but in terms of bang-for-buck, actually captured
variables in an anonymous delegate can be more convenient, plus it is
type-safe:

Thread workerThread = new Thread((ThreadS tart) delegate {
SomeFunction(so meValue); // you need to define SomeFunction
});

Here "someValue" (which could be your gridview) will be "captured" (actually
moved into a seprate class instance); everything inside the braces is
actually the outer function that will be invoked on the new thread, and is
*not* evaluated as part of the assignment to workerThread. Note that
SomeFunction can be strongly typed to accept a datagridview, rather than an
object (which is what ParameterizedTh readStart takes).

However: a bigger problem here is thread affinity. You say you need access
to datagridview - well bad news. You probably can't do much with it, as you
will get illegal thread exceptions unless you do a lot of switching between
threads (via Control.Invoke / Control.BeginIn voke). You may need to do the
processing on the background thread, and then merge the results in a single
block back on the UI thread to maintain performance.

Marc

<jo*********@to pscene.comwrote in message
news:11******** **************@ s13g2000cwa.goo glegroups.com.. .
I am using VS2005 for a windows forms application. I need to be able to
use a worker thread function to offload some processing from the UI
thread. The worker thread will need access to a datagridview on the
form. I am using the following code to spawn the worker thread...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction));
WorkerThread.Is Background = true;
WorkerThread.St art();

The problem I am having is...I cannot seem to figure out how to pass
objects into the worker thread function. For example, when I try to
use the following code...

Thread WorkerThread = new Thread(new ThreadStart(WT_ MyFunction(ref
dgvMyDataGridVi ew)));
WorkerThread.Is Background = true;
WorkerThread.St art();

...I get the compile time error: "Method name expected".

What am I doing wrong, and how can I make this work?

JP
Jul 24 '06 #9

jo*********@top scene.com wrote:
I would love to figure out how to do the processing on the background
thread. Trouble is, all of the "processing " involves iterating over the
contents of the datagridview rows.

I can plant plenty of code in the worker thread that will change the
various things in the rows via Invoke calls to the UI thread, but a
real problem is how do I get to where I can actually iterate over them
on the worker thread (foreach, etc...) - that is necessary. The way I
see it, the iteration must be done on the UI thread, period. If that is
so then I will never get rid of my screen-not-updating problem.

I have tried creating a List<DataGridVi ewRow>, and I have also tried
creating a "DataGridViewRo w[] Rowz;" and then using
dgvMyDataGridVi ew.Rows.CopyTo( Rowz). But when they get passed into the
worker thread and are evaluated, cross-thread exceptions are thrown,
just the same. It looks to me like I "copied" the rows, but at runtime
its like I tried to pass the actual rows???

There must be some way to tackle this. What would you do if you had a
datagridview with LOTS of processing that needed to be done, and all of
the processing involved iterating over the rows? Does anyone have an
idea?
I'm no expert, but what I do is gather the information I need to do
that "lots of processing" and put it in some structure completely
unrelated to the UI controls. I then launch the worker thread and have
it put its results in another structure unrelated to the UI controls.
Finally, I return control to the UI thread and copy the results into
the UI controls.

It seems like a lot of extra work, but updating the UI is usually
pretty quick. I've found a few circumstances in which it is noticeably
slow (usually ListViews with large numbers of items) but in general I
can break up the code so that trips back to the DB, for example, are in
the background thread.

In other words, it looks sort of like this:

private void SomeEvent(objec t sender, System.EventArg s e)
{
// Get info from UI controls and place it in Hashtables,
ArrayLists, whatever
// Launch the background thread
}

private void SomeEventThread Job()
{
// Do the slow stuff and put the results in Hashtables, ArrayLists,
whatever
// Invoke back to the UI thread
}

private void ContinueSomeEve nt()
{
// Copy results from output structures of SomeEventThread Job into
UI controls
}

The only one that has me stumped is a problem with creating large
numbers of ListViewItems, which seems to take a noticeable amount of
time, and can't be relegated to a background thread.

Jul 25 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
14942
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
6
2797
by: Catherine Jones | last post by:
Hi all, we need urgent help in a matter. We are trying to pass a COM object from the client to server and are facing some problems in the same. We've our client in C# as well as the Server in C# and we're using remoting for client to server communication.
1
1690
by: Ray Ackley | last post by:
I'm experiencing a threading problem that's really perplexing me. I have a multithreaded application that reads car ECU information that's sent over the serial port by the ECU and received by the laptop/program. I'll try to give a concise synopsis as the program is easily 10k+ lines. main.cs - contains the application start function. Here's the entire code (minus misc junk) as it's rather small -
3
2811
by: ExclusiveResorts | last post by:
Can the CallContext be used reliably for storing request specific data? We are developing an application library that uses the CallContext to keep an IdentityMap (hashtable of business objects that have been loaded from the DB) and a collection of business objects that have been modified during the current request. These object maps need to be globally visible throughout a request and expire at the end of it. The maps are accessed using...
10
15180
by: ChrisB | last post by:
Coming from a C/C++ background, how would I pass a function pointer to a function? I want to write a function that handles certain thread spawning. Here's what I'm trying to invision: function( thesub as <functionptr?> ) dim t as new system.threading.thread( _ new system.threading.threadstart( Addressof thesub )) .... How can I get something like that going in VB.Net?
7
1735
by: MariusI | last post by:
Are objects implicitly stored in the TLS of the currently running thread? When creating multithreaded applications i get errors when accessing data from a different thread than the thread used to create the objects (which is easely fixed by calling Invoke()). Also, is there a way to acces the thread which created the thread, or in other words: is there a parent/child relationship between threads?
5
3547
by: Soren S. Jorgensen | last post by:
Hi, In my app I've got a worker thread (background) doing some calculations based upon user input. A new worker thread might be invoked before the previous worker thread has ended, and I wan't only one worker thread running at any time (if a new worker thread start has been requested, any running worker thread results will be invalid). I'm using the below method to invoke a new worker thread, but when stress testing this I'm sometimes...
4
2811
by: Deckarep | last post by:
Hello fellow C# programmers, This question is more about general practice and convention so here goes: I got into a discussion with a co-worker who insisted that as a general practice all objects should be passed by reference using the ref keyword generally speaking because as the writer of code you are conveying your intentions that an Object should/can be modified by your function.
2
3734
by: JackC | last post by:
Hi, I create my threads like this: for(int j = 0; j < 5; j++) { boost::thread *thr = new boost::thread(worker_func); threads.add_thread(thr); }
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9174
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8096
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4517
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4782
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.