日期:2014-05-18 浏览次数:21313 次
private void button1_Click(object sender, EventArgs e) { Thread th = new Thread(aa); th.Start(); } delegate void somedle(); private void aa() { if (this.InvokeRequired) { somedle sd = new somedle(aa); this.Invoke(sd); return; } ShowChar('A'); } public void ShowChar(char ch) { lock (this) { textBox1.Text += ch; } }
------解决方案--------------------
static void Main(string[] args)
{
ManualResetEvent myResetEvent = new ManualResetEvent(false);
int X = 0;
Thread childThread = new Thread(delegate()
{
//Console.WriteLine(Thread.CurrentThread.Name + " " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Set X Value");
X = 10;
Console.WriteLine("Set X Value end");
Console.WriteLine("Notice main thread");
myResetEvent.Set();
});
childThread.Start();
while (true)
{
if (myResetEvent.WaitOne())
{
Console.WriteLine("After child thread set X, X is " + X);
myResetEvent.Reset();
}
}
Console.ReadKey();
}
这里主要是ManualResetEvent的应用,和前面的兄弟提到的autoresetevent 是差不多的,区别自己看下msdn
------解决方案--------------------
public delegate void SetIntValue(int value); public void setX(int value) { if (InvokeRequired) { // 在子线程中调用此方法时,通过Invoke转成主线程执行 Invoke(new SetIntValue(value)); return; } // 设置X值并显示 X = value; textbox.Text = X.toString(); }