shaidirendai 2014-10-04 03:05
浏览 965

提示“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);
                }
            }
        }

    }
}

}

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 stm32开发clion时遇到的编译问题