一个全局变量int a=0
for(int i=0;i<10;i++)
{
   每次生成一个线程,并且启动,
   a++;
}
有个方法为显示当前的a,可是我发现10个都是0,0000000000
如果在a++后面放上MessageBox.show(a.Tostring());
显示的是0123456789,这是MessageBox显示的
0123456789,这是那个方法显示的了。
请问大家为什么会这样呢,如何去掉MessageBox并且显示0123456789

解决方案 »

  1.   

    private int a=0;
    for(int i=0;i<10;i++)
    {
       System.Threading.ThreadStart ts=new System.Threading.ThreadStart(me);
       System.Threading.Thread t=new System.Threading.Thread(ts);
               t.Start();
    }
    private void me()
    {
    MessageBox.s(a.tostring());
    }
    就是这么个简单的问题,捆饶我好几天
      

  2.   

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Windows.Forms.Design;
    using System.Text.RegularExpressions;
    using System.Reflection;
    using System.IO;
    using System.Threading;namespace PracticeApp
    {
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.Button button1;
    private System.ComponentModel.Container components = null;
    private int a=0; public Form1()
    {
    InitializeComponent();
    } protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows 窗体设计器生成的代码
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout();
    // 
    // button1
    // 
    this.button1.Location = new System.Drawing.Point(96, 16);
    this.button1.Name = "button1";
    this.button1.TabIndex = 0;
    this.button1.Text = "Init";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(280, 266);
    this.Controls.Add(this.textBox1);
    this.Controls.Add(this.button1);
    this.Name = "Form1";
    this.Text = "Form1";
    this.ResumeLayout(false); }
    #endregion [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } private void button1_Click(object sender, System.EventArgs e)
    {
    for(int i=0;i<3;i++)
    {
    System.Threading.ThreadStart ts=new System.Threading.ThreadStart(me);
    System.Threading.Thread t=new System.Threading.Thread(ts);
    t.Start();
    a++;
    Thread.Sleep(1000);
    }
    }
    private void me()
    {
    MessageBox.Show(a.ToString());
    }
    }
    }测试通过
    如果仍有疑问,发我短消息
      

  3.   

    不好意思,多了一行代码:
    this.Controls.Add(this.textBox1);
      

  4.   

    如果把MessageBox.Show(a.ToString());换成this.TextBox1.Text+=a.ToString();
    就不行了?为什么呢。5000都不行啊
      

  5.   

    不能在非UI线程里调用UI控件的方法。