日期:2014-05-18  浏览次数:21031 次

自建类中多线程窗体显示的方法
一个窗体类Form1 一个按钮button 一个ListBox
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 WindowsApplication1
{
  public partial class Form1 : Form
  {
  aa AA = new aa();
  public Form1()
  {
  InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
  Thread t = new Thread(new ThreadStart(AA.tianjia));
  t.Start();
  }
  }
}

一个自建类 aa

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
  class aa
  {
  public void tianjia()
  {
  for (int i = 0; i < 10; i++)
  {
  string str=i
  }
  }
  }
}

如何在窗体上的ListBox中显示i的值?

------解决方案--------------------
以下例子,是在楼主你的基础上改造的,窗体上有一个按钮:button1,一个列表框:listBox1

C# code
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;

    public partial class Form2 : Form
    {
        public delegate void AddListItem(string s);//声明委托
        public AddListItem myDelegate;

        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            myDelegate = new AddListItem(AddtoListBox);

            aa AA = new aa(this);
            Thread th = new Thread(new ThreadStart(AA.tianjia));//开辟新线程
            th.Start();

        }

        public void AddtoListBox(string s)
        {
            listBox1.Items.Add(s);//给列表框添加一项
        }
        
    }
    public class aa
    {
        
        Form2 frm;
        public aa(Form2 frm)
        {
            this.frm = frm;
        }
        public void tianjia() 
        { 
            for (int i = 0; i  < 10; i++) 
            {
                frm.Invoke(frm.myDelegate, new Object[] { i.ToString() });//委托调用
            } 
        }
       

    }