0

When I try to run (debug) the program it says:

Error CS0120 An object reference is required for the non-static field, method, or property 'Form1.richTextBox1'

I want to learn how to use multiple threads in windows forms application.

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.Speech.Synthesis;
using System.Threading;


namespace test
{
public partial class Form1 : Form
{
    Thread countdown = new Thread(new ThreadStart(CountDown));

    private static SpeechSynthesizer synth = new SpeechSynthesizer();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.AppendText("A button was clicked\r\n");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        countdown.Start();
    }

    public static void CountDown()
    {
        synth.Speak("Starting!");

        for (int i = 10; i >= 0; i--)
        {
            richTextBox1.AppendText(i + "\r\n");
            System.Threading.Tasks.Task.Delay(1000).Wait();
            richTextBox1.Clear();

        }
     }
  }
}

public static void CountDown() changed to public void CountDown().

Now when I try to run (debug) the program it says:

Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.CountDown()'

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
Happy Coconut
  • 973
  • 4
  • 14
  • 33

3 Answers3

1

The first issue that you hit was the need to change public static void CountDown() to public void CountDown().

That led to the field initialization issue. You can get around that by doing this:

    Thread countdown = null;

    public Form1()
    {
        InitializeComponent();
        countdown = new Thread(new ThreadStart(CountDown));
    }

Now your program will run, however, that'll lead you in to a new issue. You'll get this error:

System.InvalidOperationException was unhandled HResult=-2146233079 Message=Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.

You simply can't access UI elements from a non-UI thread.

You'll then need to do this:

    public void CountDown()
    {
        synth.Speak("Starting!");

        for (int i = 10; i >= 0; i--)
        {
            int i2 = i; // take a local copy of the loop variable
            this.Invoke((MethodInvoker)(() => richTextBox1.AppendText(i2 + "\r\n")));
            System.Threading.Tasks.Task.Delay(1000).Wait();
            this.Invoke((MethodInvoker)(() => richTextBox1.Clear()));
        }
    }

I'd suggest trying to avoid learning how to do threading. Threading is hard and there are so many better options now.

Try using async/await and you don't need threads at all. Try this:

    private async void button2_Click(object sender, EventArgs e)
    {
        synth.Speak("Starting!");

        for (int i = 10; i >= 0; i--)
        {
            richTextBox1.AppendText(i + "\r\n");
            await System.Threading.Tasks.Task.Delay(1000);
            richTextBox1.Clear();

        }
    }
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

Each controls that you are using in the front end are non-static members, As per the rules you need An object reference is required for the non-static field, method, or property to access them inside a Static method, Here in your case the solution is simple, Change the signature of the CountDown method by removing the static keyword, so that it will also became a non-static member and you can access them as required and your code will works fine as expected.

As per this the signature of the CountDown would be like this:

public void CountDown()
{
    // Code here       
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • Hey thanks for the ansers guys! i really appreciate it. However when i remove the startic and i get another error now : Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.CountDown()' – Happy Coconut Dec 05 '16 at 03:33
-1

on button 1 click enter image description here

on button 2 click

enter image description here `

public partial class Form1 : Form
{

private static SpeechSynthesizer synth = new SpeechSynthesizer();
public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.AppendText("A button was clicked\r\n");
}

private async void button2_Click(object sender, EventArgs e)
{
    CountDown();
}

public void CountDown()
{

synth.Speak("Starting!");

    for (int i = 10; i >= 0; i--)
    {
        richTextBox1.AppendText(i + "\r\n");
        System.Threading.Tasks.Task.Delay(1000).Wait();
        richTextBox1.Clear();

    }



 }
}
}`
Siby Sunny
  • 714
  • 6
  • 14