reading and proceeding data constantly multithreading c# wpf

65 views Asked by At

I have kind of problem with multithreading, below pseudo code:

{
    float x,y,z;

    get_coordinates_from_kinect()// put them into variables x,y,z
    public void button1_Click(object sender, RoutedEventArgs e)
    {
       Thread thr = new Thread(DoStuffOnThread)
       thr.Start()
    }
    private void DoStuffOnThread()
    {
        Dispatcher.Invoke(new Action(doSomething));
    }
    void doSomething()
} 

I am getting coordinates from kinect constantly. I would like to use this data to proceed when I click button1, so I decided for multithreadnig, but the problem is when I'm pushing the button operation runs only once (one set of coordinates). I aiming to sending this data constantly. how to do this ? I'm doing my project in c# as wpf.

1

There are 1 answers

0
Denis  Yarkovoy On

You need to create and start your thread in the constructor of your class (not in the click event handler). Then create a queue (or a list) to add your coordinates to. In the DoStuffOnThread() method you should continuously (in the loop) call get_coordinates_from_kinect() and add the set of set of x,y,z to the queue. Finally, in the event handler for button click, get the items from the queue and proccess them as needed

Here is the example:

  1. Create a class to hold coordinates:
class Coords { 
  float x, y, z; 
  public Coords() { get_coordinates_from_kinect(); }
  void get_coordinates_from_kinect() { 
    // ... get coordinates and put them into x, y, z
  }
}
  1. Define a queue of coordinates in your main class:
ConcurrentQueue<Coords> queue=new ConcurrentQueue<Coords>();
  1. In the DoStuffOnThread() do this:
while (true) 
 queue.Enqueue(new Coords());
  1. In the button1_Click() do this:
Coords coord;
while (queue.TryDequeue(out coord)) {
  // ... process your coordinates as needed
}
  1. In the constructor of your main class create and start the thread:
Thread thr = new Thread(DoStuffOnThread)
thr.Start()