2009-12-19 78 views
0

好吧,我正在尝试编写一个程序,它会扫描一堆字以匹配一组字母。我希望显示的所有单词都包含用户输入的字母,我希望在程序仍在搜索时显示这些单词。因此,我必须将搜索分割到它自己的线程上,与UI线程分开。很简单。了解多线程,代表和静态

这是我到目前为止(对于一个结果文本框的简化。在我的小项目中,我根据单词长度将这些单词分割为4个不同的文本框)。

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中的非静态字段,方法或属性“消息。我不确定它想要我做什么。

我很感激帮助!

回答

2

问题是_Results是一个实例成员,但是因为_InsertWord方法是静态的,所以没有隐式实例 - 对于要解析的_Results没有“this”。 (如果你读_Resultsthis._Results - 你不需要,因为编译器在你发现_Results指向一个实例成员时插入了“this”,但它可能会更清晰)

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