线程在C#中的问题(A字段初始不能引用非静态字段,ECT) [英] Threading problems in C# (A field initializer cannot reference the non-static field, ect)
问题描述
林具有在C#中的线程一个很烦人的问题。我得到的错误一个字段初始不能引用非静态字段,方法或属性Scraper.Form1.scrapeStart()'当使用此代码:
Im having a quite annoying problem with threading in C#. I get the error "A field initializer cannot reference the non-static field, method, or property 'Scraper.Form1.scrapeStart()'" When using this code:
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;
}
}
我意识到,如果我做了功能scrapeStart静态它会的工作,但是这将使appendOutput();和button1.Enabled =真抛出的错误。如果我把在其开始(的button1_Click),那么它不能在button2_Click被终止。
I realize that if I made the function scrapeStart static it would work, but that would make appendOutput(""); and button1.Enabled = true throw errors. And if I put the new Thread in where its started (button1_Click) then it cannot be aborted in button2_Click.
我是个有点早知道C#所以我可能要么所做的一切都是新的线程可怕的错误,或者它可能只是一个小问题。但无论哪种方式,可能有人请帮助我吗?
Im a bit knew to C# so I may have either done everything horribly wrong, or it may just be a small problem. But either way, could someone please help me?
推荐答案
这真的无关线程。如果你写的,你会看到完全一样的问题:
This really has nothing to do with threading. You'll see exactly the same problem if you write:
public class Foo
{
int x = 10;
int y = x;
}
甚至更清楚:
Or even more clearly:
public class Bar
{
object obj = this;
}
这里有轻微的分心了这个
引用是隐含的 - 你要创建一个委托与这个
There's the slight distraction here that the this
reference is implicit - you're creating a delegate with a target of this
.
的目标。解决办法就是把分配到构造:
The solution is just to put the assignment into the constructor:
public Thread scrape;
public About about = new About();
public Form1()
{
InitializeComponent();
scrape = new Thread(scrapeStart);
}
顺便说一句:
As an aside:
- 请不要使用公共领域!
- 请遵守.NET命名约定
- 您会也的需要修改
scrapeStart
的螺纹部分,不应该访问的UI元素直接
- Please don't use public fields!
- Please adhere to .NET naming conventions
- You'll also need to fix the threading parts of
scrapeStart
, which shouldn't be accessing UI elements directly
这篇关于线程在C#中的问题(A字段初始不能引用非静态字段,ECT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!