Domanda

Presently, I have a windows form that is receiving data from a named pipe asynchronously. To avoid getting the "Cross thread operation not valid: Control 'myTextBox' accessed from a thread other than the thread it was created on" I am using an anonymous method (see http://www.codeproject.com/Articles/28485/Beginners-Guide-to-Threading-in-NET-Part-of-n):

            // Pass message back to calling form
            if (this.InvokeRequired)
            {
                // Create and invoke an anonymous method
                this.Invoke(new EventHandler(delegate
                {
                    myTextBox.Text = stringData;
                }));
            }
            else
                myTextBox.Text = stringData;

My question is, what does the "new EventHandler(delegate" line do? Does it create a delegate of a delegate? Could someone please explain, how would I implement the above functionality using a named delegate instead (just to help with understanding it)? TIA.

È stato utile?

Soluzione

If you have a C++ background, I'd describe delegates as simple pointers to functions. Delegates are .NET's way of safely handling function pointers.

To used a named delegate, you first have to create a function to handle the event:

void MyHandler(object sender, EventArgs e)
{
    //Do what you want here
}

Then, for your previous code, change it to this:

this.Invoke(new EventHandler(MyHandler), this, EventArgs.Empty);

If I were doing this though, I'd write it like this to avoid duplicate code.

EventHandler handler = (sender, e) => myTextBox.Test = stringData;

if (this.InvokeRequired)
{
    this.Invoke(handler, this, EventArgs.Empty);  //Invoke the handler on the UI thread
}
else
{
    handler(this, EventArgs.Empty); //Invoke the handler on this thread, since we're already on the UI thread.
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top