Thursday, 13 September 2007

Cross Thread Safety with anonymous methods

When working with multithreading and async operations you will no doubt get a message that you have tried to execute a cross thread operation which is not allowed. Times like this I would make a delagte reflection of the method I wish to use, and then invoke the target control, passing in the arguments the function requires.

A little easier way which requires only one delegate is the following. Create you delegate for example:


private delegate void InvokeDel();

Then in my sample project for example, I have a small network app and when a client connects I add the remote end point or IPAddress:PortNo to the list view. Because I am doing this with Async this needs to be cross thread safe so I did the following:



private void AddClient(Socket _client)
{

this.Invoke(new InvokeDel(delegate()
{
listView1.Items.Add(new ListViewItem(new string[] { _client.RemoteEndPoint.ToString(), _client.SocketType.ToString() }));
}));
}

This works find and uses anonymous methods.

No comments: