Hi, I did simple exercise with threads and this problem occurred:
The application has one form (Form1), one label (label1), one button (button1), one string (myString) and one method (myMethod).The idea is when button1 is clicked content from myString to be displayed in label1.I use new thread myThread which is started using delegate ts.
The problem is that the content of the string is not displayed in label1.
If add MessageBox in myMethod content of the string can be displayed in MessageBox(but not in label1) when button1 is clicked.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace QuestionThread
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(myMethod);
Thread myThread = new Thread(ts);
myThread.Start();
label1.Text = myString;
}
string myString;
private void myMethod()
{
myString = "Something";
//if add MessageBox content of the string can be displayed in MessageBox(but not in label1) when button1 is clicked
MessageBox.Show(myString);
}
}
}
Thanks
Tanmay SarkarPosted Jul 16, 2010, 11:56 AM
use it in button1 code:
private void button1_Click(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(myMethod);
Thread myThread = new Thread(ts);
myThread.Start();
Thread.Sleep(100);
label1.Text = myString;
}
just put Thread.Sleep(100); & it will show that you want.
Please mark it as ans if it help you.
Thank you!