Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#螺纹错误_C#_Multithreading - Fatal编程技术网

C#螺纹错误

C#螺纹错误,c#,multithreading,C#,Multithreading,因此,我试图创建一个自动打字机。问题是,如果我发送垃圾邮件,然后单击应用程序停止垃圾邮件,它就会冻结。然后我被告知我需要使用线程。所以我仔细阅读了一下,得出了以下结论: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using Sys

因此,我试图创建一个自动打字机。问题是,如果我发送垃圾邮件,然后单击应用程序停止垃圾邮件,它就会冻结。然后我被告知我需要使用线程。所以我仔细阅读了一下,得出了以下结论:

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()'
我做错了什么(

提前感谢,,
阿兰娜。

我不会浪费您的时间来解决这个错误。相反,考虑使用现有的方法来在.NET中编写多线程应用程序。您使用的技术将取决于您正试图解决的问题类型。对于短/快任务,请考虑使用:

  • 线程池
  • .net任务库
如果你正在创建一个“长时间”运行的任务,你可以创建一个或多个本机线程,但我不建议你在更好地理解你正在做的事情之前这样做。有很多陷阱。例如,许多开发人员认为线程越多,性能就越好……这不是真的

参考资料

  • 线程池:
  • 任务:
  • 本机线程:

该错误告诉您它是什么:字段初始值设定项(
threadtest=new Thread(spam);
)无法引用非静态方法
tf2trade.Form1.spam()
。您也确实不想从按钮的单击处理程序中调用该垃圾邮件方法。@但是,如果我将其设置为静态,则会产生更多错误。另外,我应该怎么做而不是从单击处理程序中调用它呢?不要从字段初始值设定项中创建树。创建线程,例如在构造函数中,或者使用其他方法d、 您不想在单击处理程序中调用该方法,因为它包含
Thread.Sleep
,这将停止UI线程,导致应用程序停止响应用户输入。