2009-12-19 44 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文本框的線程之外的線程上運行。