An object reference is required for the non-static field method or property/field initializer cannot reference the non-static field method or property

I was making a program and I stumbled across this two-in-one problem, where the first problem leads to the other. I have not yet found a question where someone had both problems leading into eachother. I'm still learing, and have learned a lot from other problems I had, but I can't find a solution to this problem.

It has to do with threading. I want to make a thread, that can place something in a rich textbox every second or so, while I can still press buttons to start and stop it. But to make a function that a thread can run, I need to make the function static. Otherwise I'll get the error "A field initializer cannot reference the non-static field, method, or property". But when a function is static, it cannot acces any of the created items, like richTextBox1. Because if I try to change it's text, I get the error "Error 1 An object reference is required for the non-static field, method, or property". And if I fix this by removing static, the thread will not work.

I made a demo program that is smaller than the full one, but has the same problem. Button1 is the button to start the thread, Button2 is the one to stop it.

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 threading_non_static_problem_demo
{
    public partial class Form1 : Form
    {
        static Thread thr = new Thread(new ThreadStart(demofunc));
        int checkthr = 0; //int to check if the thread has been running before (I like to do things like this)
        int ifthrrun = 0; //int to check if the thread is running
        public Form1()
        {
            InitializeComponent();
            button2.Enabled = false; // so you can't click the "stop" button if nothing is running
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
        }
        static void demofunc()
        {
            while (true)
            {
                Thread.Sleep(1000);
                richTextBox1.Text = richTextBox1.Text + "text added"; // <-- here's the problem
                MessageBox.Show("tried to add text"); // you can use this messagebox to check if the thread is working correctly
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (checkthr == 0) // check if the thread has run before, 0 is no, 1 is yes, and then start or resume it
            {
                thr.Start();
                ifthrrun = 1;
                button2.Enabled = true;
                button1.Enabled = false;
            }
            else if (checkthr == 1)
            {
                thr.Resume();
                ifthrrun = 1;
                button2.Enabled = true;
                button1.Enabled = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            thr.Suspend();
            checkthr = 1;
            ifthrrun = 0;
            button2.Enabled = false;
            button1.Enabled = true;
        }
        protected override void OnFormClosing(FormClosingEventArgs e) // if the program is closing, check the thread's state and act accordingly
        {
            if (ifthrrun == 0)
            {
                if (checkthr == 1)
                {
                    thr.Resume();
                    thr.Abort();
                }
                else if (checkthr == 0)
                {
                }
            }
            else if (ifthrrun == 1)
            {
                thr.Abort();
            }
        }
    }
}

To use this code just creat a forms application, add two buttons, and a rich text box, it should work.

Thank you in advance for you answers.


ANSWERS:


But to make a function that a thread can run, I need to make the function static.

Get rid of the static declarations and move initialization of your "thr" variable to the constructor like this:

    Thread thr;

    public Form1()
    {
        InitializeComponent();
        button2.Enabled = false; // so you can't click the "stop" button if nothing is running
        thr = new Thread(new ThreadStart(demofunc));
        Control.CheckForIllegalCrossThreadCalls = false;
    }

    private void demofunc()
    {
        while (true)
        {
            Thread.Sleep(1000);
            richTextBox1.Text = richTextBox1.Text + "text added"; // <-- problem "solved" by disabling Control.CheckForIllegalCrossThreadCalls
        }
    }

But ignore the above "fix" because using Suspend()/Resume() is not recommended.

See Pausing and Resuming Threads:

Important

Starting with the .NET Framework version 2.0, the Thread.Suspend and Thread.Resume methods are marked obsolete and will be removed in a future release.

The Thread.Suspend and Thread.Resume methods are not generally useful for applications and should not be confused with synchronization mechanisms. Because Thread.Suspend and Thread.Resume do not rely on the cooperation of the thread being controlled, they are highly intrusive and can result in serious application problems like deadlocks (for example, if you suspend a thread that holds a resource that another thread will need).

One way to be able to pause/resume your loop would be to use a ManualResetEvent like this:

    Thread thr;
    ManualResetEvent mre = new ManualResetEvent(false);

    public Form1()
    {
        InitializeComponent();
        button2.Enabled = false; // so you can't click the "stop" button if nothing is running
        thr = new Thread(new ThreadStart(demofunc));
    }

    private void demofunc()
    {
        while (!this.IsDisposed && !this.Disposing)
        {
            Thread.Sleep(1000);
            if (!this.IsDisposed && !this.Disposing)
            {
                this.Invoke((MethodInvoker)delegate {

                    richTextBox1.AppendText("text added");

                });
            }
            mre.WaitOne();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
        mre.Set();
        if (!thr.IsAlive)
        {
            thr.Start();
        }
        button2.Enabled = true;
    }

    private void button2_Click(object sender, EventArgs e)
    { 
        button2.Enabled = false;
        mre.Reset();
        button1.Enabled = true;
    }

    protected override void OnFormClosing(FormClosingEventArgs e) // if the program is closing, check the thread's state and act accordingly
    {
        mre.Set(); // make sure the loop continues so it can drop out
    }

}


 MORE:


 ? C# should Singleton contain static methods?
 ? C# should Singleton contain static methods?
 ? C# should Singleton contain static methods?
 ? Should private helper methods be static if they can be static
 ? Should C# methods that *can* be static be static?
 ? Non static members in Singleton class
 ? Invalid use of non-static member function - Class Member Function Calling Another Class Member Function
 ? Invalid use of non-static member function - Class Member Function Calling Another Class Member Function
 ? Invalid use of non-static member function - Class Member Function Calling Another Class Member Function
 ? invalid use of non-static member function