C#中的线程问题(字段初始值设定项不能引用非静态字段等)

Alp*_*lta 0 c# multithreading syntax-error

我在C#中遇到一个非常烦人的问题.我收到错误"字段初始值设定项不能引用非静态字段,方法或属性'Scraper.Form1.scrapeStart()'"使用此代码时:

public partial class Form1 : Form
{
    public Thread scrape = new Thread(() => scrapeStart()); //This is where the error happens
    public About about = new About();
    public Form1()
    {
        InitializeComponent();
    }

    public void appendOutput(String s)
    {
        output.AppendText(s);
        output.SelectionStart = output.Text.Length;
        output.ScrollToCaret();
        output.Refresh();
    }

    public void scrapeStart(){
        Button button1 = new Button();
        appendOutput("");
        button1.Enabled = true;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        about.ShowDialog();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
        scrape.Start();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        scrape.Abort();
        button1.Enabled = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到,如果我使用scrapeStart函数静态它会工作,但这会使appendOutput(""); 和button1.Enabled = true抛出错误.如果我将新线程放在它开始的位置(button1_Click),那么它就不能在button2_Click中中止.

我对C#有点了解,所以我可能要么做了一切可怕的错误,要么可能只是一个小问题.但无论哪种方式,有人可以帮助我吗?

Jon*_*eet 10

这与线程无关.如果你写的话,你会看到完全相同的问题:

public class Foo
{
    int x = 10;
    int y = x;   
}
Run Code Online (Sandbox Code Playgroud)

甚至更清楚:

public class Bar
{
    object obj = this;
}
Run Code Online (Sandbox Code Playgroud)

这里有一个轻微的分心,即this引用是隐式的 - 你正在创建一个目标为的委托this.

解决方案只是将赋值放入构造函数中:

public Thread scrape;
public About about = new About();
public Form1()
{
    InitializeComponent();
    scrape = new Thread(scrapeStart);
}
Run Code Online (Sandbox Code Playgroud)

作为旁白:

  • 请不要使用公共领域!
  • 请遵守.NET命名约定
  • 需要修复scrapeStart不应直接访问UI元素的线程部分