using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace WindowsApplication1
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
public void Display()
{
for (int index = 1; index <= 100000; index++)
{
// Generate two random numbers and assign to Top and Left of Label
// Random object
Random objRandom = new Random(); // Location Variables
int x = 0;
int y = 0; x = objRandom.Next(this.Width);
y = objRandom.Next(this.Height);
lblX.Left = x;
lblX.Top = y;
Thread.Sleep(500); }
}
public void DisplayEnglish()
{
for (int index = 1; index <= 100000; index++)
{
// Generate two random numbers and assign to Top and Left of Label
// Random object
Random objRandom = new Random(); // Location Variables
int x = 0;
int y = 0; x = objRandom.Next(this.Width);
y = objRandom.Next(this.Height);
lblG.Left = x;
lblG.Top = y;
Thread.Sleep(100);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Create a thread
Thread draw = new Thread(new ThreadStart(Display));
// Invoke thread // Create a thread
Thread drawEnglish = new Thread(new ThreadStart(DisplayEnglish));
// Invoke thread
draw.Start();
drawEnglish.Start();
draw.IsBackground = true;
drawEnglish.IsBackground = true;
}
}
}我用VS2003运行一切正常,但是用C# 2005运行后就报个异常``汗``错误信息如下:
lblX.Left = x;
线程间操作无效: 从不是创建控件“Form1”的线程访问它。
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace WindowsApplication1
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
public void Display()
{
for (int index = 1; index <= 100000; index++)
{
// Generate two random numbers and assign to Top and Left of Label
// Random object
Random objRandom = new Random(); // Location Variables
int x = 0;
int y = 0; x = objRandom.Next(this.Width);
y = objRandom.Next(this.Height);
lblX.Left = x;
lblX.Top = y;
Thread.Sleep(500); }
}
public void DisplayEnglish()
{
for (int index = 1; index <= 100000; index++)
{
// Generate two random numbers and assign to Top and Left of Label
// Random object
Random objRandom = new Random(); // Location Variables
int x = 0;
int y = 0; x = objRandom.Next(this.Width);
y = objRandom.Next(this.Height);
lblG.Left = x;
lblG.Top = y;
Thread.Sleep(100);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Create a thread
Thread draw = new Thread(new ThreadStart(Display));
// Invoke thread // Create a thread
Thread drawEnglish = new Thread(new ThreadStart(DisplayEnglish));
// Invoke thread
draw.Start();
drawEnglish.Start();
draw.IsBackground = true;
drawEnglish.IsBackground = true;
}
}
}我用VS2003运行一切正常,但是用C# 2005运行后就报个异常``汗``错误信息如下:
lblX.Left = x;
线程间操作无效: 从不是创建控件“Form1”的线程访问它。
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货