views:

105

answers:

1

Okay, I'm trying to write a program that will scan a bunch of words to match against a set of letters. I want all words displayed that contain the letters entered by the user and I want these words displayed while the program is still searching. Therefore, I have to split the search onto its own thread, separate from the UI thread. Easy enough.

Here's what I have so far (simplified for one results TextBox. In my little project, I'm splitting the words to 4 different TextBoxes based on the word length).

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";
}

The problem I'm running into is that when I try to pass the word back to the delegate function, _InsertWord, and assign it to the _Results.Text, it gives me the "An object reference is required for the non-static field, method or property" message on _Results.Text. I'm not sure what it wants me to do.

I appreciate the help!

+2  A: 

The problem is that _Results is an instance member, but because your _InsertWord method is static, there is no implicit instance -- no "this" for _Results to be resolved against. (It may be clearer if you read _Results as this._Results -- you don't need to write that, because the compiler inserts the "this" for you when it figures out that _Results refers to an instance member -- but it may help it to be more explicit in your mind.)

The simplest fix is therefore to make _InsertWord and _SearchForWords instance methods, so they can have access to instance members like _Results. However, note that if you do this, you will need to use Control.BeginInvoke or Control.Invoke to update the text, because _InsertWord is running on a thread other than the one which owns the _Results text box.

itowlson