using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;namespace PrimeTest
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private Thread primeThread;
private System.Windows.Forms.ListBox lstPrime;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnPause;
private System.Windows.Forms.Button btnResume;
private System.Windows.Forms.Button btnStop;          /// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null) 
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.lstPrime = new System.Windows.Forms.ListBox();
this.btnStart = new System.Windows.Forms.Button();
this.btnPause = new System.Windows.Forms.Button();
this.btnResume = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.SuspendLayout();
// 
// lstPrime
// 
this.lstPrime.ItemHeight = 12;
this.lstPrime.Location = new System.Drawing.Point(8, 16);
this.lstPrime.Name = "lstPrime";
this.lstPrime.Size = new System.Drawing.Size(336, 160);
this.lstPrime.TabIndex = 0;
// 
// btnStart
// 
this.btnStart.Location = new System.Drawing.Point(8, 192);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 1;
this.btnStart.Text = "开始(&S)";
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
// 
// btnPause
// 
this.btnPause.Location = new System.Drawing.Point(96, 192);
this.btnPause.Name = "btnPause";
this.btnPause.TabIndex = 2;
this.btnPause.Text = "暂停(&P)";
this.btnPause.Click += new System.EventHandler(this.btnPause_Click);
// 
// btnResume
// 
this.btnResume.Location = new System.Drawing.Point(177, 192);
this.btnResume.Name = "btnResume";
this.btnResume.TabIndex = 3;
this.btnResume.Text = "恢复(&R)";
this.btnResume.Click += new System.EventHandler(this.btnResume_Click);
// 
// btnStop
// 
this.btnStop.Location = new System.Drawing.Point(264, 192);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 4;
this.btnStop.Text = "停止(&O)";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
// 
// Form1
// 
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(352, 237);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnResume);
this.Controls.Add(this.btnPause);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.lstPrime);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() 
{
Application.Run(new Form1());
} private void btnStart_Click(object sender, System.EventArgs e)
{
//新线程
primeThread = new Thread(new ThreadStart(Generate));
//线程名
primeThread.Name = "质数"; btnPause.Enabled = true;
btnStart.Enabled = false;
btnStop.Enabled = true;
primeThread.Start();
} private void Form1_Load(object sender, System.EventArgs e)
{
btnPause.Enabled = false;
btnStop.Enabled = false;
btnResume.Enabled = false;
}
public void Generate()
{
            //CheckForIllegalCrossThreadCalls   
          
// true = 质数; false  = 非质数
bool IsPrime = true;
int count = 2;
//由于第一个质数是2,因此将它添加到列表中         //   Thread.CurrentThread.Name = "test";
lstPrime.Items.Add(2);
//执行循环直到生成另外24个质数
for(int i = 3; count < 50; i += 2)
{
IsPrime = true;
for (int j = 2; j <= (i /2); j++)
{
//检查"i"是否 可以被整除
if(i % j == 0)
{
IsPrime = false;
break;
}
}
 
// 显示质数并递增计数器
    lock(this)
{
if(IsPrime)
{
lstPrime.Items.Add(i);
count++;
//使线程休眠100毫秒,以启用线程的暂停和恢复
Thread.Sleep(100);
}
}
}
//线程完成后,启用和禁用这些按
this.btnStart.Enabled = true;
btnPause.Enabled = false;
btnStop.Enabled = false;
btnResume.Enabled = false;
} private void btnPause_Click(object sender, System.EventArgs e)
{
try
{
if(primeThread.ThreadState == ThreadState.Running
|| primeThread.ThreadState == ThreadState.WaitSleepJoin)
{
primeThread.Suspend(); btnPause.Enabled = false;
btnResume.Enabled = true;
btnStop.Enabled = false; }
}
catch(ThreadStateException ce)
{
MessageBox.Show(ce.ToString(),"异常");
}
}
private void btnStop_Click(object sender, System.EventArgs e)
{
btnStop.Enabled = false;
btnStart.Enabled = true;
btnPause.Enabled = false;

 
primeThread.Abort();


} private void btnResume_Click(object sender, System.EventArgs e)
{
if(primeThread.ThreadState == ThreadState.Stopped 
|| primeThread.ThreadState == ThreadState.SuspendRequested 
|| primeThread.ThreadState == ThreadState.WaitSleepJoin 
|| Convert.ToInt32(primeThread.ThreadState) == 96)
{
try
{
primeThread.Resume();
btnResume.Enabled = false;
btnPause.Enabled = true;
btnStop.Enabled = true;
}
catch(ThreadStateException ce)
{
MessageBox.Show(ce.ToString(),"异常");
}
}
}
}}听网友说:
Control.CheckForIllegalCrossThreadCalls = false;可是不知在哪里设置,“点”不出来,急啊

解决方案 »

  1.   

    可以在构造函数里设置..this.CheckForIllegalCrossThreadCalls =false;
      

  2.   

    把this.CheckForIllegalCrossThreadCalls =false;
    放在
    Form1_Load函数里
      

  3.   

    最好的办法是用委托...你出现这个问题主要是因为你在线程方法中操作了界面上的控件..lstPrime.Items.Add()可以这样改下..//定义一个委托
    public delegate void MyInvoke(string str);//定义一个操作界面的方法
    private void UpdateUI(string str)
    {
        //增加项
        this.lstPrime.Items.Add(str);
    }
    //在线程的方法中,即你的Generate方法..
    //里面只要是涉及到Items.Add操作的都改成如下形式即可..
    //比如lstPrime.Items.Add(2);改成:
    MyInvoke mi=new MyInvoke(UpdateUI);
    this.BeginInvoke(mi,new object[]{"2"});
      

  4.   

    this.CheckForIllegalCrossThreadCalls =false;这种做法不行。错误 2 无法使用实例引用访问静态成员“System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls.get”;改用类型名来限定它 J:\C#项目实战\BankNumber\BankRandNumber\BankRandNumber\Form1.cs 64 13 BankRandNumber用 this 点不出来
      

  5.   

    TO:用 this 点不出来不好意思,说错了,直接这样就行了,写在构造函数中:CheckForIllegalCrossThreadCalls = false;
      

  6.   

    这个异常好像是在debug模式下2005会捕捉 2003责会没有 帮助文档上有解决方法的例子 跟前面有人说用委托是一样的 你可以链接到抛出的这个异常的解释说明去看下 我今天也碰到相识的问题 也查了下的 不知道有没有帮助
      

  7.   

    在msdn帮助里有两种方法的例子
    可以参考
      

  8.   


    //创建聊天线程
    public:System::Void MyChatProcess()
    {
      array<unsigned char>^ MyReceivedByte=gcnew array<unsigned char>(65);
      String^ MyReceivedString;
      if(MyAcceptSocket->Connected)
      {
        this->label5->Text="准备聊天!";
    while(MyChattingState)
    {
    MyAcceptSocket->Receive(MyReceivedByte,MyReceivedByte->Length,SocketFlags::None);
    MyReceivedString=Encoding::BigEndianUnicode->GetString(MyReceivedByte); this->listBox1->Items->Add(MyReceivedString);
    }
      }
    }
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
    this->MyChattingState=true;
    }
    //创建聊天室
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
      Thread^ MyThread;
      try
      {
    MyHostIP=IPAddress::Parse(this->textBox1->Text);
    MyServer=gcnew IPEndPoint(MyHostIP,Int32::Parse("1234"));
    MySocket=gcnew Socket(AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp);
    MySocket->Bind(MyServer);
    MySocket->Listen(50);
    this->label5->Text="服务器已经处于监听状态";
        MyAcceptSocket=MySocket->Accept();
    ThreadStart^ MyDelegate = gcnew ThreadStart(this,&Example::Form1::MyChatProcess);
    MyThread = gcnew Thread(MyDelegate);
    MyThread->Start();
      }
      catch(Exception^ MyEx)
      {
         this->label5->Text=MyEx->Message;
      }
    }
    //关闭聊天室
    private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
      try
      {
    MySocket->Close();
    MyAcceptSocket->Close();
        this->label5->Text="成功断开与客户端程序的连接!";
      }
      catch(Exception^ MyEx)
      {
          this->label5->Text="客户端程序可能不存在!";
      }
    }
    //发送信息
    private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
      array<unsigned char>^ MySentByte=gcnew array<unsigned char>(65);
      String^ MySendString;
      try
      {
    MySendString=this->textBox2->Text+"::"+this->richTextBox1->Text;
    MySentByte=Encoding::BigEndianUnicode->GetBytes(MySendString->ToCharArray());
    MyAcceptSocket->Send(MySentByte,MySentByte->Length,SocketFlags::None);
    this->richTextBox1->Text="";
      }
      catch(Exception^ MyEx)
      {
          this->label5->Text=MyEx->Message;
      }
    }
    };
    }遇到的问题和楼主是一样的,就是不知道在哪改,各位大侠帮忙看下!
      

  9.   

     public Form1()
            {
                InitializeComponent();
             }
    加上CheckForIllegalCrossThreadCalls = false;
    好用!但是委托就不会用了!
      

  10.   

    System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;