473,804 Members | 2,064 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

foreach listviewitem in a background thread

How can I have access to the items collection of a listview control on
my form from a background thread?

I know I need delegates to update the listview control and I have those
calls in the foreach loop, but I'm not sure how to access the items
collection.

foreach (ListViewItem li in this.listview1. Items)
{
Invoke(new deleg(updatectr l), new object [] { param });
}

Thanks!
May 15 '07
13 10240
On Thu, 17 May 2007 08:23:26 -0700, deciacco <a@awrote:
[...]
I was thinking something like this:

************
private delegate void setScriptStatus ImageDelegate(i nt imgIndex, int
listItemIndex);

this.listviewPr ogress.Invoke(n ew
setScriptStatus ImageDelegate(s etScriptStatusI mage), new object[] { 0,
lvi.Index });

private void setScriptStatus Image(int imgIndex, int listItemIndex)
{
this.listviewPr ogress.Items[listItemIndex].ImageIndex = imgIndex;
}
************

The problem is, I still get the cross-thread error on lvi.Index.
I thought I should be able to pass in lvi.Index since I used a delegate
to get lvi.
Nope. Sorry. :) Going through Invoke (note that it's the Invoke that's
important, not the delegate...thou gh Invoke does of course require a
delegate) is what prevents the cross-thread problem, and it applies only
during the actual execution of Invoke. You get the same object back via
Invoke as you would calling directly, and all the same rules apply to that
object.

(By the way, there *are* mechanisms that actually do convert certain kinds
of objects from one execution environment to another, whether that's
cross-thread, cross-process, cross-network, etc...it's known as
"marshaling ". So it wasn't unreasonable of you to think maybe what you
wanted to do was possible. It just turns out that in this case, what's
being "marshaled" is the code execution, not any of the data being used)..

You can get the reference to the ListViewItem and handle that safely in
the thread, but any operations on it have to follow the same rules as
apply to the ListView object itself. So, you can Invoke to get the
reference to it, and then you can pass that reference back to the UI
thread via Invoke for doing something else, but you can't actually *do*
anything with the reference on the worker thread.

Fortunately, none of this is a big problem. You may have already figured
out the solution, but just in case...

If you want to pass an index rather than the ListViewItem itself, you can
just change the code to look like this:

private delegate void setScriptStatus ImageDelegate(i nt imgIndex, int
listItemIndex);

this.listviewPr ogress.Invoke(n ew
setScriptStatus ImageDelegate(s etScriptStatusI mage), new object[] { 0,
iitem });

private void setScriptStatus Image(int imgIndex, int listItemIndex)
{
this.listviewPr ogress.Items[listItemIndex].ImageIndex = imgIndex;
}
and then the loop looks like this:

for (int iitem = 0; iitem < citem; iitem++)
{
// Use Invoke to actually change the image index
this.listviewPr ogress.Invoke(n ew
setScriptStatus ImageDelegate(s etScriptStatusI mage), new object[] { 0,
iitem });
Thread.Sleep(20 00);
this.listviewPr ogress.Invoke(n ew
setScriptStatus ImageDelegate(s etScriptStatusI mage), new object[] { 0,
iitem });
}

The main problem being that you are now even more exposed to the
possibility of the ListView changing between calls. Not that that problem
didn't exist before, but at least if there was a bug, you would still
always update the icon for the same ListViewItem (though by the time you
get to updating it, it would be possible that it wasn't the ListViewItem
corresponding to the processing you're doing, depending on how you
correlate your ListViewItem instances when the processing iteration).
With the above code, if there's a bug you could actually wind up setting
the icon 0 for one ListViewItem and then setting the icon 1 for a
different ListViewItem later.

Obviously the best solution is to not have bugs where you modify or
otherwise lose correlation with the ListView while it's still in use. :)
Just something to be aware of. The two versions of the code aren't
functionally equivalent, but as long as you understand the differences, I
think that's fine.

Pete
May 17 '07 #11
That was a very long explanation, so thank you for your time...great help!!!

Peter Duniho wrote:
On Thu, 17 May 2007 08:23:26 -0700, deciacco <a@awrote:
>[...]
I was thinking something like this:

************
private delegate void setScriptStatus ImageDelegate(i nt imgIndex, int
listItemIndex) ;

this.listviewP rogress.Invoke( new
setScriptStatu sImageDelegate( setScriptStatus Image), new object[] { 0,
lvi.Index });

private void setScriptStatus Image(int imgIndex, int listItemIndex)
{
this.listviewPr ogress.Items[listItemIndex].ImageIndex = imgIndex;
}
************

The problem is, I still get the cross-thread error on lvi.Index.
I thought I should be able to pass in lvi.Index since I used a
delegate to get lvi.

Nope. Sorry. :) Going through Invoke (note that it's the Invoke
that's important, not the delegate...thou gh Invoke does of course
require a delegate) is what prevents the cross-thread problem, and it
applies only during the actual execution of Invoke. You get the same
object back via Invoke as you would calling directly, and all the same
rules apply to that object.

(By the way, there *are* mechanisms that actually do convert certain
kinds of objects from one execution environment to another, whether
that's cross-thread, cross-process, cross-network, etc...it's known as
"marshaling ". So it wasn't unreasonable of you to think maybe what you
wanted to do was possible. It just turns out that in this case, what's
being "marshaled" is the code execution, not any of the data being used).

You can get the reference to the ListViewItem and handle that safely in
the thread, but any operations on it have to follow the same rules as
apply to the ListView object itself. So, you can Invoke to get the
reference to it, and then you can pass that reference back to the UI
thread via Invoke for doing something else, but you can't actually *do*
anything with the reference on the worker thread.

Fortunately, none of this is a big problem. You may have already
figured out the solution, but just in case...

If you want to pass an index rather than the ListViewItem itself, you
can just change the code to look like this:

private delegate void setScriptStatus ImageDelegate(i nt imgIndex, int
listItemIndex);

this.listviewPr ogress.Invoke(n ew
setScriptStatus ImageDelegate(s etScriptStatusI mage), new object[] { 0,
iitem });

private void setScriptStatus Image(int imgIndex, int listItemIndex)
{
this.listviewPr ogress.Items[listItemIndex].ImageIndex = imgIndex;
}
and then the loop looks like this:

for (int iitem = 0; iitem < citem; iitem++)
{
// Use Invoke to actually change the image index
this.listviewPr ogress.Invoke(n ew
setScriptStatus ImageDelegate(s etScriptStatusI mage), new object[] { 0,
iitem });
Thread.Sleep(20 00);
this.listviewPr ogress.Invoke(n ew
setScriptStatus ImageDelegate(s etScriptStatusI mage), new object[] { 0,
iitem });
}

The main problem being that you are now even more exposed to the
possibility of the ListView changing between calls. Not that that
problem didn't exist before, but at least if there was a bug, you would
still always update the icon for the same ListViewItem (though by the
time you get to updating it, it would be possible that it wasn't the
ListViewItem corresponding to the processing you're doing, depending on
how you correlate your ListViewItem instances when the processing
iteration). With the above code, if there's a bug you could actually
wind up setting the icon 0 for one ListViewItem and then setting the
icon 1 for a different ListViewItem later.

Obviously the best solution is to not have bugs where you modify or
otherwise lose correlation with the ListView while it's still in use.
:) Just something to be aware of. The two versions of the code aren't
functionally equivalent, but as long as you understand the differences,
I think that's fine.

Pete
May 17 '07 #12
On Thu, 17 May 2007 10:41:41 -0700, deciacco <a@awrote:
That was a very long explanation, so thank you for your time...great
help!!!
"Feed a man a fish, teach a man to fish..." :)

I could've just written your code for you, but I hope in the long run you
know more now. The long-term goal is, of course, to get you to the point
where *you* are answering *my* questions. :)
May 17 '07 #13
I agree with you completely...

I don't want the code written for me, I want someone to help me
understand, but it's so difficult to find people willing to do that and
it is difficult to communicate through newsgroups or email.

Peter Duniho wrote:
On Thu, 17 May 2007 10:41:41 -0700, deciacco <a@awrote:
>That was a very long explanation, so thank you for your time...great
help!!!

"Feed a man a fish, teach a man to fish..." :)

I could've just written your code for you, but I hope in the long run
you know more now. The long-term goal is, of course, to get you to the
point where *you* are answering *my* questions. :)
May 23 '07 #14

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

Similar topics

1
323
by: Ahsan | last post by:
I have created some background threads so that when the application aborts all the threads should be automatically aborted. But the problem is that when I make a thread background thread I am unable to correctly find its thread state as the thread state property always return 12. If I make the thread foreground the thread state property works just fine. Please help me in finding the solution.
2
5471
by: jam | last post by:
dear all, could anyone help me about telling me how can i make a background thread displaying loading... when I cam calling a console application?? thanks.. jam
1
7003
by: Ioannis Vranos | last post by:
In .NET, what happens when a background thread and a foreground thread have the same priority (e.g. Normal). Do they share the same processor time? -- Ioannis Vranos
0
1033
by: Bil Muh | last post by:
Hello Developers, I would like to fill a data grid on my "Windows Forms (.NET)" by a background thread. I read some data from a binary file. With the information read from this file, I create Columns and Rows dynamically, then I fill them. I can do this operation. But, when the numbers of rows and columns are much, my application uses the 99% of CPU and stops working for other works. Fot this reason, I tried to assign this job to a...
0
1735
by: JC Voon | last post by:
Hi All: I'm new in Threading and Web Services, can someone please verify my code, i'm not sure whether this is the correct way, althought it is partially work, but some time it will raise exception at FillDatatable dr.AcceptChanges, and also the XTraGridControl will not response when click on the column header to do sorting and filtering. What i'm trying to do is very simple, i just want to retrieve a very large table from web service...
1
4253
by: JEB | last post by:
I know that with Web Services, you should be doing everything in a stateless environment. However, I have three methods out of over 100 that need state. I have the client cookie container, WebMethod with Session enabled = true, the works. However, my issue is I am running logic on a background thread in a managed thread pool and I cannot access the session. I cannot pass all the data into the thread either. Is there a way to access...
8
12100
by: mtsweep | last post by:
Hi, I started a background thread to preform some time intensive tasks for a GUI frontend. This background thread uses a C++ object which requires a windows message loop so I started one in it by calling Application.Run(). Now I can see that messages from the C++ libraries are being processed. But how do I send my own messages to this thread from the GUI frontend? I tried to use delegates/events/etc but it ends up either spawning a...
8
5375
by: =?Utf-8?B?R3JlZyBMYXJzZW4=?= | last post by:
I'm trying to figure out how to modify a panel (panel1) from a backgroundworker thread. But can't get the panel to show the new controls added by the backgroundwork task. Here is my code. In this code there is a panel panel1, that I populate with a lable in the foreground. Then when I click on "button1" a backgroundworker thread in async mode is started. When the backgoundworker thread completes the thread returns a panel to populate...
1
1876
by: Matt | last post by:
I've written a class that allows me to add documents to a SharePoint Document Library from another web application. The web app runs under a domain account that has permissions to SharePoint. However, when I try to do this from a background thread it fails with Access Denied. I've tested the WindowsIdentity from the background thread and it is the same. Are background threads not running in the same security context under ASP.NET 2.0? ...
0
9716
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
9595
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,...
0
10604
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10354
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10101
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9177
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...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4314
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
3005
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.