Problems with C #

What I'm doing is a list that is dynamically created from the previous button. Then ti launches a background worker, in which you should clear the list and fill iistview with new information every 30 seconds.
I keep getting: Cross-threading is not valid: Control 'listView2' is accessible from a stream other than the stream on which it was created.

private void watcherprocess1Updatelist() { listView2.Items.Clear(); string betaFilePath1 = @"C:\Alpha\watch1\watch1config.txt"; using (FileStream fs = new FileStream(betaFilePath1, FileMode.Open)) using (StreamReader rdr = new StreamReader((fs))) { while (!rdr.EndOfStream) { string[] betaFileLine = rdr.ReadLine().Split(','); using (WebClient webClient = new WebClient()) { string urlstatelevel = betaFileLine[0]; string html = webClient.DownloadString(urlstatelevel); File.AppendAllText(@"C:\Alpha\watch1\specificconfig.txt", html); } } } 
+3
c #
Apr 05 '10 at 17:29
source share
3 answers

You cannot access your ListView element from a background thread. You need to do this in the user interface thread.

There are two options: first, you can switch this to use Windows.Forms.Timer to run every 30 seconds. This will happen in the user interface thread, which will completely fix this problem, but move the processing to the user interface thread. If your processing is slow, it can lead to a hang.

Alternatively, use Control.Invoke to redirect calls in the ListView back to the user interface stream:

  listView2.Invoke(new Action( () => listView2.Items.Clear() ) ); 

In any case, I would rethink the use of BackgroundWorker. It is not intended for “temporary events” that occur at regular intervals. You should consider switching to Windows.Forms.Timer (UI thread) if long processing is not performed, or System.Timers.Timer (running in the background thread) if processing takes some time. This is a better design option than BackgroundWorker, which never ends.

+6
Apr 05 '10 at 17:32
source share

You need to use Control.Invoke to call the code in the user interface thread to update the listView.

+2
Apr 05 '10 at 17:30
source share

Here is the pattern that I use for methods that will be randomly controlled using the user interface

 public void DoSomethingToUI(string someParams) { if(UIControl.InvokeRequired) { UIControl.BeginInvoke(()=>DoSomethingToUI(someParams)); return; } //Do something to the UI Control } 
+2
Apr 05 '10 at 17:39
source share



All Articles