0

I found many posts about the update of GUI from another thread but it goes in every direction. I hope someone can explain me the better way for my application.

I have a form with a GMap.Net control to display a map. I created a thread that will collect Lat,Long positions from a database, do some computations and let the GUI display those position as markers on the map.

In Form1.cs:

private void pictureBox1_Click(object sender, EventArgs e)
{
    if (!_acquisitionClick)
    {
        _position.Start();
        _acquisitionClick = true;
    }
}

In DevicePosition.cs:

public void Start()
{
    _posThread = new Thread(new ThreadStart(StartPositionAcquisition));
    _posThread.Start();
}

public void StartPositionAcquisition()
{
     while(Thread.CurrentThread.IsAlive)
     {
         //Get positions from database and and do some computation
         Thread.Sleep(2000);
     }
}

Now I would like to update my form according to a status changed by the thread to indicate that new data has arrived.

What is the best method in:

1) Backgroundworker with _DoWork() where I get the positions and perform the computations and _RunWorkerCompleted() where I update the map. Found here: http://www.albahari.com/threading/part3.aspx#_BackgroundWorker

2): Using Thread with the Dispatcher.Invoke method used in the thread to update directly the map. If this is a good solution, how does it work exactly in this situation ? Found here: https://stackoverflow.com/a/661662/4010683

3): Using Thread with events like ProgressEvent that let the main thread know that new data have arrived and the update of the map should proceed...

4): Something else that I missed ?

Thank you for your help on this. Btw I'm using VS 2012 with .Net 4.5 on Win 7 32 bits.

Community
  • 1
  • 1
Robert Jones
  • 587
  • 7
  • 25
  • @paul I'm using WinForms for this project – Robert Jones Jul 31 '15 at 15:51
  • Just a tip, if your using .net 4.5 then use Task or Task if you want to return a value rather than Thread or BackgroundWorker. – Ben Robinson Jul 31 '15 at 15:52
  • @BenRobinson Is there a real difference in performance between the two types Thread and Task or is it only to respect the higher level of abstraction and to avoid creating your own thread ? – Robert Jones Jul 31 '15 at 15:56
  • Its the higher level of abstraction, you can concentrate more on getting your logic right without so much time spent marshalling threads. – Ben Robinson Jul 31 '15 at 15:59
  • @BenRobinson All right, so using: `await Task.Factory.StartNew(() => Position.StartPositionAcquisition(), TaskCreationOptions.LongRunning);` and then in the StartPositionAcquisition I have an infinite loop would be a good solution ? What about if I want to sleep the task for 1 second and during this second I want to update my GUI with data the task computed ? – Robert Jones Aug 03 '15 at 08:48

0 Answers0