Ouais Alsharif
Ouais Alsharif

Reputation: 327

Events Fired in Background Thread Ignored

I'm running a C# forms application which starts a thread to acquire some data. This thread has some events inside it i.e: the events fire in the thread and are supposed to be captured by the same thread. However, the thread's events don't seem to be firing. Any clues?

private void btnPlay_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(kinect.onlineRun);
        thread.IsBackground = true;
        thread.Start();
    }

inside the thread:

void PointCreated(object sender, IdEventArgs e) // a certain event that should fire and it doesn't
        {
            Console.WriteLine("Event Fired!");            
        }



public void onlinerun()
{
    Console.WriteLine("run started"); // this is printed on console
    while (true)
    {
      do_some_work();
      //this work could result in the PointCreated event firing
    }
}

Upvotes: 1

Views: 229

Answers (1)

TeamWild
TeamWild

Reputation: 2550

Give something like this a try:

Assuming your calling class is called Controller and your delegate is called ControlEventHandler...

private void PointCreated(object sender, IdEventArgs e)
{
    // Ensure the event was received in the calling thread
    if (this.InvokeRequired)
    {
        if (e != null)
        {
            // We aren't in the correct thread so pass on the event
            this.BeginInvoke(new Controller.ControllerEventHandler(this.PointCreated), new object[] { sender, e });
        }
    }
    else
    {
        lock (this)
        {
            Console.WriteLine("Event Fired!");

            // TODO: Do some stuff here
        }
    }
}

Upvotes: 1

Related Questions