views:

40

answers:

1

I got following code executing at a ~1000ms rate. Left alone, it causes a weird "thread leak". Using WindDBG/SoS I am able to see waaay to many ThreadPool Worker threads (some of them are marked as dead) and eventually I will get a AccessVioalation Exception. Can anybody tell me if my BeginInvoke/EndInvoke use is wrong, unnecessary lock perhaps ... any clues will help as I am ... well, clueless at this point

RichTextBox tmpBox = txtIncomingData;

lock (m_TextUpdateSynch) {
   try {
       result = Utilities.SafeBeginInvoke(this, delegate() {
           try {
               if (tmpBox.Text.Length > BufferSize) {
                   tmpBox.Text = rawData;
               }
               else {
                   tmpBox.AppendText(rawData);
               }
               pageBottom(txtIncomingData);
           }
           catch (...) {}
       });
       this.EndInvoke(result);
   }


    public static IAsyncResult Utilities.SafeBeginInvoke(System.ComponentModel.ISynchronizeInvoke control, 
ControlUpdate action, AsyncCallback callback, 
params object[] args) {
        IAsyncResult result = null;

        Control uiControl = control as Control;
        try {
            result = control.BeginInvoke(action, args);
        }
        catch (...) { }

        return result;
    }
+1  A: 

It looks like your code is using WPF, and it's my understanding that in WPF BeginInvoke will marshall the call you;re making to the UI (Dispatcher) thread; so it shouldn't be creating any extra threads as far as I'm aware.

http://msdn.microsoft.com/en-us/library/ms591206.aspx

I notice your try/catch pairs around the BeginInvoke call too; this suggests to me that you've been getting exceptions thrown by that, and I'd suggest that getting to the root of them might be a better plan than suppressing them. For example you seem to be referencing three variables - BufferSize, rawData, txtIncomingData which are defined outside of your lock - if any other code has a reference to them and is modifying them on a different (non-UI) thread then that could be causing your issues.

Lastly, I think the overload of SafeBeginInvoke you listed isn't the one being called by the code - the one listed takes 4 parameters (although one is params), the one you call takes 2.

Tom Carver
true about the overloaded method, there is one that accepts 2 parameters and passes nulls for callback and args if not needed. No WPF here, just Winforms - and my money is on the use of EndInvoke being used wrong - but I will looks closer at the variables being used on a different thread.
kermit_xc