我如何在此程序中使用线程?

时间:2012-03-21 06:19:44

标签: c# .net c#-4.0 c#-3.0

我已经编写了这个控制台应用程序来搜索文件中的特定字符串并查看它是否存在..但我想只打开主程序中的文件。并包括10个不同的线程同时找到10个不同的单词..我尝试使用线程,但我没有做对..我怎么做?有人可以帮我代码吗?这是我的计划..

class Program
{
    static void Main(string[] args)
    {
        Thread T = new Thread(Finding);
        T.Start();
        using (System.IO.StreamReader Reader = new System.IO.StreamReader("C://myfile2.txt"))

        {
            StringBuilder Sb = new StringBuilder();
            string fileContent = Reader.ReadToEnd();
            if (fileContent.Contains("and"))
            {
                Console.WriteLine("It is Present");
            }
            else
            {
                Console.WriteLine("It is not Present");
            }

            Console.ReadLine();
        }
    }
    static void Finding()
    {
        if (fileContent.Contains("hello"))
        {
            Console.WriteLine("It is Present");
        }
        else
        {
            Console.WriteLine("It is not Present");
        }
    }
}

1 个答案:

答案 0 :(得分:3)

var text = File.ReadAllText("somePath");

foreach (var word in new[]{"word1", "word2", "word3"})
{
    var w = word;

    new Thread(() => Console.WriteLine("{0}: {1}",
                                       w,
                                       text.Contains(w) ? "Yes" : "No")).Start();
}

您应该知道字符串不能包含无限字符,因此如果内容对于字符串来说太大,您可以将File.ReadAllLines(“path”)用于“行”而不是File.ReadAllText(“path”) )进入“文本”并替换

text.Contains(w)

lines.Any(l => l.Contains(w))

如果您认为可能找到所有单词,您还可以使用File.ReadLines()来做一些复杂的事情,以避免在没有必要时读取所有行。