问题描述
- 提示“Label1不是从创建它的线程访问”,怎么修改,请问?
-
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 CallBackEx
{
public partial class Form1 : Form
{
public delegate void ExampleCallback(int lineCount,Label lb);
public Form1()
{
InitializeComponent();
}
public void CurrentNumber(int tempNumber, Label lb)
{
lb.Text = tempNumber.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadWithData twd = new ThreadWithData(1, 100, this.label1, new ExampleCallback(CurrentNumber));
Thread td = new Thread(new ThreadStart(twd.RunMethod));
td.Start();
}private void button2_Click(object sender, EventArgs e) { ThreadWithData twd = new ThreadWithData(2, 200, this.label2, new ExampleCallback(CurrentNumber)); Thread td = new Thread(new ThreadStart(twd.RunMethod)); td.Start(); } public class ThreadWithData { private int start=0; private int end=0; private ExampleCallback callback; private Label lb; public ThreadWithData(int start,int end,Label lb,ExampleCallback callback) { this.start = start; this.end = end; this.callback = callback; this.lb = lb; } public void RunMethod() { for (int i = start; i < end; i++) { Thread.Sleep(500); if (callback != null) { callback(i,lb); } } } } }
}
时间: 2024-11-08 20:25:44