tags:

views:

90

answers:

1

This is modified code I found on this site.

When appending text to a TextBox and InvoveRequired is false the text will display in the box but the next time the function is called and InvokeRequired is true the text string placed by the first call is lost (""). Multiple calls when InvokeRequired is true work as expected.

comBox is a type TextBox with multline = true.

Any help would be appreciated.

 public void LogComText(string comText, bool newline)
    {
        if (comBox.InvokeRequired)
        {

            comBox.BeginInvoke(new Action(delegate
            {
                LogComText(comText, newline);
            }));
            return;
        }
        comBox.AppendText(comText);
        if (newline) comBox.AppendText(Environment.NewLine);


    }
+2  A: 

This looks like it should work, maybe it has some thing to do with concurrency.
Try using comBox.Invoke(...) instead of comBox.BeginInvoke(...)
Update: The thing is when you use BeginInvoke the method calls may be invoked out of order.
That was wrong, calls to Invoke and BeginInvoke are executed in order.

Edit:
It that doesn´t work make sure you don´t have any other place where you change the text in comBox.

If it still doesn´t work you might have to create a lock to make sure you don´t have two thread simultaneously writing to the textbox.

Something like this:

private static readonly object _comBoxSyncObj = new object();
public void LogComText(string comText, bool newline)
{
    if (comBox.InvokeRequired)
    {
        comBox.Invoke(new Action(delegate
        {
            LogComText(comText, newline);
        }));
        return;
    }
    lock (_comBoxSyncObj)
    {
        comBox.AppendText(comText);
        if(newline) comBox.AppendText(Environment.NewLine);
    }
}

Edit2:
If the problem persists, you can add an event handler for the TextChanged event and put a breakpoint in it to se when the textbox get cleared.

Add this method and an eventhandler for TextChanged on comBox:

private void comBox_TextChanged(object sender, EventArgs e)
{
    if (comBox.TextLength == 0)
    {
        // Set a breakpoint here.
        Trace.WriteLine("TextBox empty");
    }
}
Jens Granlund
Both Invoke and beginInvoke have the same result. I'll try the lock and post back.
Tom
Control.BeginInvoke, "Executes a delegate asynchronously on the thread that the control's underlying handle was created on."BeginInvoke just adds a message to the queue for the UI thread. Those messages will be processed in the order they were created.
hemp
@hemp, you´r right. I thought about the `ThreadPool.QueueUserWorkItem`.
Jens Granlund