我正在尝试将一个字符串数组分成 2 个,创建 2 个线程并在这 2 个线程上搜索这些数组。我知道我正在正确地创建线程,并且搜索功能是正确的,但我仍然收到此错误:
System.NullReferenceException was unhandled
Object reference not set to an instance of an object.
这是代码:
// Create first and second array:
string[] firstarray = pieces.Take(pieces.Length / 2).ToArray();
string[] secondarray = pieces.Skip(pieces.Length / 2).ToArray();
string[] results = new string[pieces.Length];
string inputword = textBox5.Text.Trim();
ManualResetEvent[] calls = new ManualResetEvent[2];
calls[0] = new ManualResetEvent(false);
calls[1] = new ManualResetEvent(false);
// Set 2 new threads:
ThreadPool.QueueUserWorkItem((t) => {
// SearchThruPieces searches an array for a string and returns the items
// that contains the string
// SearchThruPieces(string[] pieces, string word);
SearchThruPieces(firstarray, inputword).CopyTo(results, 0);
calls[0].Set();
});
ThreadPool.QueueUserWorkItem((t) => {
SearchThruPieces(secondarray, inputword).CopyTo(results, firstarray.Length);
calls[1].Set();
});
WaitHandle.WaitAll(calls);
string firststring = results[0]; // This line throws an exception
现在我知道这个错误与任何线程或SearchThruPieces
方法无关,因为它发生在我使用时:
results[0]
它返回错误。
请帮我解决这个问题或告诉我他们是否是做我想要完成的事情的更好方法。
谢谢
编辑:
这是 SearchThruPieces 的代码:
delegate string[] Search(string[] pieces, string word);
static Search SearchThruPieces = (string[] pieces, string word) =>
{
object locker = new object();
lock (locker)
{
int a = 0;
string[] afterpieces = new string[pieces.Length];
for (int b = 0; b < (pieces.Length / 4); b++)
{
if (pieces[a].Trim().ToLower().Contains(word.Trim().ToLower()) && pieces[a].Trim().Length > 0)
{
afterpieces[a] = pieces[a].Trim();
afterpieces[a + 1] = pieces[a + 1].Trim();
afterpieces[a + 2] = pieces[a + 2].Trim();
afterpieces[a + 3] = pieces[a + 3].Trim();
}
a += 4;
}
return afterpieces;
}
};
编辑2:
所以我设置了一个断点:
afterpieces[a] = pieces[a].Trim();
看看它是否被调用,它确实如此。我认为该错误与将 results[] 设置为SearchThruPieces
.