手动和自动同时访问全局变量时,就有可能出现线程不同步的问题。以下主要利用lock线程锁来修改解决方案,使线程同步,详细代码如下。
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 treadTest
{
//定义委托
public delegate void ListBoxDelegate();
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//委托处理方法(关联与ListBoxDelegate)
private void ListBox()
{
if (!listBox1.InvokeRequired)//如果在UI主线程操作ListBox,
{
listBox1.Items.Add(CommonData.plus());//则直接进行控件操作,“与UI主线程相关联”
listBox1.SelectedItem = listBox1.Items[listBox1.Items.Count - 1];
}
else//如果是在另一线程操作ListBox,则启用委托
listBox1.Invoke(new ListBoxDelegate(listS