user1710944
user1710944

Reputation: 1459

update my label in different Thread and wait for the result

In my application I am start process (Tshark) and start capturing, after I am finish to capturing I am checking the created file and parse from the process output the number of received packets in order to update my UI. in this point if the created file is big all the UI stuck until the result on number of packets received so I want to do it in different Thread.

Capinfos capInfo = new Capinfos(); //my class who return the number of packets
ThreadStart tStarter = delegate {label.Text = capInfo._numberOfPackets.ToString("#,##0"); };
Thread thread = new Thread(tStarter);
thread.IsBackground = true;
thread.Start();

This code return a cross threading error.

Upvotes: 0

Views: 253

Answers (2)

Tejas Sharma
Tejas Sharma

Reputation: 3440

It appears that you're trying to update the UI using a thread other than the UI thread (label.Text = ---). I think that is probably what the problem is. You could use Tasks to achieve asynchrony. You could use the Task's ContinueWith method to wait on the task to finish before updating your UI thread using BeginInvoke. http://msdn.microsoft.com/en-us/library/dd235678.aspx

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499860

You're doing it the wrong way round. You should be performing the packet capture in a different thread, only accessing the UI elements within the UI thread.

There are loads of different ways of doing this. The most common are probably:

  • You can use Control.Invoke and Control.BeginInvoke to marshal back to the UI thread when you need to
  • You can use BackgroundWorker which does some of this for you; you'd hook up the progress reporting event to update the UI from the right thread
  • If you're using C# 5 and .NET 4.5 you could use async/await to automatically get back to the UI thread within a single asynchronous method

Upvotes: 1

Related Questions