I think the title speaks for itself. Simply I have some threads that run with a random order instead of the order I planned. This is a sample code:
event strHandler strChanged;
delegate void strHandler(string str);
public Form1()
{
InitializeComponent();
strChanged += new strHandler(updatestr);
}
public void updatestr(string str)
{
Thread th = new Thread(new ParameterizedThreadStart(updatethr));
th.IsBackground = true;
th.Start(str);
}
object obj = new object();
private void updatethr(object str)
{
lock (obj)
{
SystemUtilities.SetControlPropertyThreadSafe(textBox1, "Text", (string)str);
Thread.Sleep(1000);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Text = write();
}
private string write()
{
string res = "";
strChanged(res);
for (int i = 0; i <= 5; i++)
{
res += i.ToString();
strChanged(res);
}
return res;
}
Note: SystemUtilities.SetControlPropertyThreadSafe(textBox1, "Text", (string)str) is a function (used to avoid cross thread exception) that set textBox1.Text to str. When you press button1 this.Text will be set instantly to the result of write() function ("012345"). The string returned is res that is build inside write() starting from an empty string and, iteratively, appending numbers from 0 to 5. When the string is created and for each number added to res, the event strChanged is raised calling updatestr method. Every time that updatestr is called a thread is created and it starts calling updatethr. Here textBox1.Text is set to str (that should be progressively "", "0" , "01", "012", "0123", "01234", "012345") and wait a second before exiting the method. Using lock statement the threads created in updatestr should wait the end of the previous threads before modifying textBox1.Text. Running this code I obtain sequences of values for textBox1.Text that don't match the expected sequence as if the threads don't start in order with their creation in updatestr. Why does this happen? How can I fix that? Thanks in advance!
EDIT: If want to try this code you can replace SystemUtilities.SetControlPropertyThreadSafe(textBox1, "Text", (string)str) with System.Windows.Forms.MessageBox.Show(str)
Aucun commentaire:
Enregistrer un commentaire