理解多线程,委托和静态

时间:2009-12-19 02:47:55

标签: multithreading static delegates scope

好吧,我正在尝试编写一个程序来扫描一堆单词以匹配一组字母。我希望显示的所有单词都包含用户输入的字母,我希望在程序搜索时显示这些单词。因此,我必须将搜索拆分为自己的线程,与UI线程分开。很容易。

这是我到目前为止所得到的(简化了一个结果TextBox。在我的小项目中,我根据单词长度将单词拆分为4个不同的TextBox)。

static string _challengeString;
static string[][] _categorizedWords = new string[26][];
Thread _letterSearch = new Thread(new ParameterizedThreadStart(_SearchForWords);

public MainForm()
{
   // do the work to load the dictionary into the _categorizedWords variable
   // 0 = A, 1 = B, .., 24 = Y, 25 = Z;

   // build the form which contains:
   // 1 TextBox named _entryChars for user entry of characters
   // 1 Button named _btnFind
   // 1 TextBox named _Results
   InitializeComponent;  

}

private void FindButton_Click(object sender, EventArgs e)
{
   _letterSearch.Abort();
   _letterSearch.IsBackground = true;
   _challengeString = _entryChars.Text;

   _Results.Text = "";

   for (int letterIndex = 0; letterIndex < 26; letterIndex++)
   {
      _letterSearch.Start(letterIndex);
   }
   _entryChars.Text = "";
}

static void _SearchForWords(object letterIndex)
{
   Regex matchLetters = new Regex( _challengeString, RegexOptions.IgnoreCase | RegexOptions.Compiled );

   foreach (string word in _categorizedWords[(int)letterIndex])
   {
      if ( matchLetters.Match(word).Success )
      {
         _InsertWord(word);
      }
   }
}

delegate void InsertWord(string word);
public static void _InsertWord(string word)
{
   _Results.Text += word + "\n";
}

我遇到的问题是,当我尝试将单词传递给委托函数_InsertWord,并将其分配给_Results.Text时,它给了我“非对象引用是必需的_Results.Text上的静态字段,方法或属性“message”。我不确定它要我做什么。

我很感激帮助!

1 个答案:

答案 0 :(得分:2)

问题是_Results是一个实例成员,但因为你的_InsertWord方法是静态的,所以没有隐式实例 - 没有“this”可以解析_Results。 (如果您将_Results视为this._Results可能会更清楚 - 您不需要编写,因为编译器在编写时会为您插入“this”并且_Results指的是实例成员 - 但它可能有助于它在你的脑海中更明确。)

因此,最简单的修复方法是生成_InsertWord和_SearchForWords实例方法,这样他们就可以访问像_Results这样的实例成员。但是,请注意,如果执行此操作,则需要使用Control.BeginInvoke或Control.Invoke来更新文本,因为_InsertWord在拥有_Results文本框的线程以外的线程上运行。