2014-10-20 49 views
0

所以即时尝试创建一个自动typer。问题是如果我发送垃圾邮件,并点击应用程序停止垃圾邮件只是冻结。然后我告诉我需要使用线程。所以我有一个围绕阅读,这就是我想出了:C#线程错误

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Threading; 

namespace tf2trade 
{ 
    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 
     } 
     public bool started = true; 

     private void spam() 
     { 
      string test = text1.Text; 
      Thread.Sleep(2000); 
      while (started == false) 
      { 
       foreach (char c in test) 
       { 
        SendKeys.Send(c.ToString()); 
       } 
       SendKeys.Send("{ENTER}"); 
      } 
     } 

     Thread test = new Thread(spam); 

     private void richTextBox1_TextChanged(object sender, EventArgs e) 
     { 

     } 

     private void submit_Click(object sender, EventArgs e) 
     { 


      if (started == true) 
      { 
       started = false; 
       submit.Text = "Stop"; 
       submit.Refresh(); 
       spam(); 
      } 
      else 
      { 
       started = true; 
       submit.Text = "Start"; 
      } 




     } 
    } 
} 

下面这段代码给我的错误:

A field initializer cannot reference the non-static field, method, or property 'tf2trade.Form1.spam()' 

我做了什么错? :(

在此先感谢, 阿拉纳。

+0

这个错误告诉你很可能它是什么:一个字段初始值( 'Thread test = new Thread(spam);')不能引用非静态方法'tf2trade。 Form1.spam()'。您也不想从按钮的点击处理程序中调用该垃圾邮件方法。 – poke 2014-10-20 01:41:13

+0

@poke但是,如果我使它静态,它会创建更多的错误。另外我应该做什么,而不是从点击处理程序调用它? – 2014-10-20 01:44:30

+0

请勿从字段初始值设定项创建trehad。创建线程,例如在构造函数或其他方法中。而且你不想在click处理程序中调用该方法,因为它包含'Thread.Sleep',并且会停止UI线程,导致应用程序停止响应用户输入。 – poke 2014-10-20 01:45:49

回答

1

老实说,我不会浪费你的时间解决此错误,而是考虑利用现有的方法来使用.NET编写多线程应用程序之一,技术您使用将取决于你试图解决问题的类型对于短期/快速任务考虑使用:

  • 线程池
  • .NET任务库

如果您正在创建一个“长期”运行任务,您可以创建一个或多个本地线程,但我不会建议您这样做,直到您对自己的工作有更好的理解。有很多陷阱。例如,许多开发人员认为更多的线程等于更好的性能......这是不正确的。

参考文献