线程同步问题
线程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);