james
james

Reputation: 1041

Multiple Invoke / BeginInvoke calls not finishing without Thread.Sleep()

In the below code is run within a background worker thread:

while (StaticVideoList.DecodedFramesList.Count > 0)
{
    if (StaticVideoList.DecodedFramesList.ContainsKey(a))
    {
        byte[] output;

        if(StaticVideoList.DecodedFramesList.TryRemove(a, out output))
        {

            MemoryStream ms = new MemoryStream(output);

            Image img = Image.FromStream(ms);

            a++;

            this.Invoke((Action)delegate
            {
                textEdit7.Text = "Num Frame: " + a.ToString() + " / " + (1000m / ((decimal)sw.ElapsedMilliseconds / (decimal)a)).ToString();
                pictureEdit1.Image = img;
            });

            // Works if I do this.. 10 is the minium. 
            //System.Threading.Thread.Sleep(10);
        }
    }

}

My issue is unless I add a Thread.Sleep(10) within the loop not all of the Invoke calls are made. The whole loop is called but only 20% of the invoke calls are made (it gets 20% in then stops, not intermittent results)

If i step through in debugging it works fine as well.

Thought maybe the issue was when the Background Worker thread finishes it cancels any Invokes made from it. But putting a Thread.Sleep(10000) to hang the background thread up longer didn't do anything.

Is there a limit to how fast you can make invoke calls?

Also BeginInvoke has the same "issue"

Upvotes: 1

Views: 199

Answers (1)

James
James

Reputation: 82096

Invoke to me would appear to be a red herring. The fact that the loop appears to "stop" but works when you sleep the thread would suggest to me that you have a race condition.

My advice would be strip your loop back to the bare minimum & rebuild it until you hit the issue again - that should help you identify where the problem is.

Upvotes: 1

Related Questions