Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading in C# produces errors

I am using this code:

private void Form1_Load(object sender, EventArgs e)
{

}

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string response = serialPort1.ReadLine();
    this.BeginInvoke(new MethodInvoker(
        () => textBox1.AppendText(response + "\r\n")
    ));
}

ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();

but am getting lots of errors:

Error 2 The type or namespace name 'ThreadStart' could not be found (are you missing a using directive or an assembly reference?) C:\Users\alexluvsdanielle\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 31 44 WindowsFormsApplication1

Error 3 The name 'ThreadWork' does not exist in the current context C:\Users\alexluvsdanielle\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 31 56 WindowsFormsApplication1

Error 4 The type or namespace name 'Thread' could not be found (are you missing a using directive or an assembly reference?) C:\Users\alexluvsdanielle\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 32 31 WindowsFormsApplication1

Error 5 A field initializer cannot reference the non-static field, method, or property 'WindowsFormsApplication1.Form1.myThreadDelegate' C:\Users\alexluvsdanielle\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 32 38 WindowsFormsApplication1

What am I doing wrong?

like image 665
Alex Gordon Avatar asked Dec 02 '22 05:12

Alex Gordon


1 Answers

Perhaps I'm mentioning the bleedin' obvious here, but from the code example, your code block:

ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();

Is not in a method. I have done this before.

Once you have fixed this, the other answers will obviously then apply.

like image 69
Tim Lloyd Avatar answered Dec 17 '22 19:12

Tim Lloyd