Alana Stephens
Alana Stephens

Reputation: 119

C# Thread error

So im attempting to create a auto typer. And the problem is if i spam the message, And click the application to stop the spam it just freezes up. I as then told i need to use Threads. So i had a read around and this is what i came up with:

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";
            }




        }
    }
}

Now this code gives me the error:

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

What did i do wrong? :(

Thanks in advance, Alana.

Upvotes: 0

Views: 1519

Answers (1)

Pressacco
Pressacco

Reputation: 2875

Honestly I wouldn't waste your time troubleshooting this error. Instead, consider using one of the existing approaches to writing multi-threaded applications in .NET . The technology you use will depend on the type of problem you are trying to solve. For short/quick tasks consider using:

  • thread pool
  • .net task library

If you are creating a "long" running task you could create 1 or more native threads, but I wouldn't recommend doing this until you have a better understanding of what you are doing. There are a lot of pitfalls. For example, A lot of developers think more threads equals better performance... this is not true.

REFERENCES

Upvotes: 2

Related Questions