For example modifying the example from http://msdn.microsoft.com/en-US/library/a1hetckb(v=vs.80) to read
expand collapse
public void Run() { myFormControl1.myListBox.Items.Add("test from thread");...
works in non-debug mode:
namespace WindowsFormsApplication1 { public partial class MyFormControl : Form { public delegate void AddListItem(string myString); public AddListItem myDelegate; private Button myButton; private Thread myThread; public ListBox myListBox; private Button myNoThreadButton; public MyFormControl() { //InitializeComponent(); myButton = new Button(); myNoThreadButton = new Button(); myListBox = new ListBox(); myButton.Location = new Point(72, 160); myButton.Size = new Size(152, 32); myButton.TabIndex = 1; myButton.Text = "Add items in list box"; myButton.Click += new EventHandler(Button_Click); myNoThreadButton.Location = new Point(70, 190); myNoThreadButton.Size = new Size(100, 32); myNoThreadButton.Text = "Add items No thread created"; myNoThreadButton.Click += new EventHandler(ButtonNoThread_Click); myListBox.Location = new Point(48, 32); myListBox.Name = "myListBox"; myListBox.Size = new Size(200, 95); myListBox.TabIndex = 2; ClientSize = new Size(332, 333); Controls.AddRange(new Control[] { myListBox, myButton, myNoThreadButton }); Text = " 'Control_Invoke' example "; myDelegate = new AddListItem(AddListItemMethod); } static void Main() { MyFormControl myForm = new MyFormControl(); myForm.ShowDialog(); } public void AddListItemMethod(String myString) { myListBox.Items.Add(myString); } private void Button_Click(object sender, EventArgs e) { myThread = new Thread(new ThreadStart(ThreadFunction)); myThread.Start(); } private void ButtonNoThread_Click(object sender, EventArgs e) { for (int i = 1; i <= 5; i++) { string myString = "(no thread) Step number " + i.ToString() + " executed"; AddListItemMethod(myString); } } private void ThreadFunction() { MyThreadClass myThreadClassObject = new MyThreadClass(this); myThreadClassObject.Run(); } } public class MyThreadClass { MyFormControl myFormControl1; public MyThreadClass(MyFormControl myForm) { myFormControl1 = myForm; } String myString; public void Run() { myFormControl1.myListBox.Items.Add("test from thread"); for (int i = 1; i <= 5; i++) { myString = "Step number " + i.ToString() + " executed"; Thread.Sleep(400); // Execute the specified delegate on the thread that owns // 'myFormControl1' control's underlying window handle with // the specified list of arguments. myFormControl1.Invoke(myFormControl1.myDelegate, new Object[] { myString }); } } }
Just when I thought the group couldn’t get greater, you detect ways to make it happen!This article is a good one !!! Thanks so much for all you have put into it.
ReplyDeletehttp://www.dapfor.com/en/net-suite/net-grid/features/performance