线程同步问题
线程A一直做一件事情。主界面线程如果要访问A对象中某个数据,要停止A线程的更新,避免我要读取的数据被A线程删除了。我做了个例子。但发现例子有问题。请您帮我调试一下,新建工程。WindowsApplication
以下是Form3.CS
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace LearnProject
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
MyUpdate = new MyUpdateDelegate(UpdateText);
System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(MyThreadProc));
ThreadRunEnable = true;
th.Start();
}
private volatile bool ThreadRunEnable = false;
private void MyThreadProc()
{
const string strConst = "This is a test sentence.";
int i = 0,istrLen = strConst.Length;
try
{
while (ThreadRunEnable && i < int.MaxValue)
{
System.Threading.Thread.Sleep(80);
Monitor.Enter(Sync);
this.Invoke(MyUpdate, new object[] { strConst[i % istrLen].ToString() });
Monitor.Exit(Sync);
i++;
Application.DoEvents();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.StackTrace+"\r\n"+ex.Message);
return;
}
//MessageBox.Show("Thread abort.");
}
private MyUpdateDelegate MyUpdate;
private delegate void MyUpdateDelegate(string strText);
public void UpdateText(string strText)
{
textBox1.AppendText(strText);
textBox1.Update();
}
private void button1_Click(object sender, EventArgs e)
{
Monitor.Enter(Sync);
textBox1.AppendText("\r\n");
Monitor.Exit(Sync);
}
private void button2_Click(object sender, EventArgs e)
{
//m_Mutex.WaitOne();
ThreadRunEnable = false;
//m_Mutex.ReleaseMutex();
}
private volatile object Sync = new object();
//private volatile System.Threading.AutoResetEvent eventMutex = new System.Threading.AutoResetEvent(false);
private void Form3_FormClosing(object sender, FormClosingEventArgs e)
{
//m_Mutex.WaitOne();
ThreadRunEnable = false;
//m_Mutex.ReleaseMutex();
//m_Mutex.WaitOne();
//m_Mutex.ReleaseMutex();
}
private void button3_Click(object sender, EventArgs e)
{
System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(MyThreadProc));
ThreadRunEnable = true;
th.Start();
}
}
}