C#线程问题和最佳实践 [英] C# Threading issue & best practices

查看:89
本文介绍了C#线程问题和最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次在C#应用程序中使用线程.基本上,它是一个应用程序,用于检查列表中的一堆网站是否已死或存活.

This is my 1st time using threading in an C# Application. Basically its an application which checks a bunch of web sites in a list whether its dead or alive.

这是我第一次尝试使用多线程

Here is my 1st attempt to work with multi-threading

    public void StartThread(string URL,int no)
    {
        Thread newThread = new Thread(() =>
        {
            BeginInvoke(new Action(() => richTextBox1.Text += "Thread " + no + " Running" + Environment.NewLine));
            bool b = ping(URL);
            if (b == true) { BeginInvoke(new Action(() => richTextBox2.Text += "Okay" + Environment.NewLine)); }
            else
            { return; }
        });

        newThread.Start();
    }

我正在使用上述函数创建新线程,并且每个线程都在循环内创建.

I'm using the above function to create new threads and each thread is created inside a loop.

foreach(网站中的字符串网站){ StartThread(site,i); i ++; //计数器}

foreach (string site in website) { StartThread(site,i); i++; // Counter }

由于我是初学者,所以我有几个问题.

Since i'm a beginner i have few questions.

  1. 代码工作正常,但我不确定这是否是最佳解决方案
  2. 有时线程运行完美,但有时线程不会从方法 ping()中返回任何值,该方法将检查主机,如果使用WebRequest联机则返回true.这很平常吗?
  3. 如果我要求用户指定他需要使用的线程数,那么我如何在这些线程之间平均分配工作?
  4. 我跟踪线程状态(死/活)的一种优雅方式是吗?我目前使用rocess.GetCurrentProcess().Threads.Count;
  1. The code works fine but i'm not sure if this the best solution
  2. Sometimes threads run perfectly but sometimes Threads does not return any values from the method ping() which checks the host and returns true if its online using WebRequest. is it usual ?
  3. If i ask the user to specify a no of threads that he needs to use , how can i equally distribute work among those threads ?
  4. Is their an elegant way that i track the status of the thread, ( dead / alive ) ? i currently use rocess.GetCurrentProcess().Threads.Count;

推荐答案

1)您的解决方案确定. 任务类,如果您正在编写新代码,则可以使用它. .NET 4.5中还有一个全新的东西,叫做 await 但是,请参见4).

1) Your solution is OK. The Thread class has been partially superseded by the Task class, if you're writing new code, you can use that. There is also something completely new in .NET 4.5, called await .However, see 4).

2)如果网站已死,您的ping方法可能只是崩溃.您可以向我们展示该方法的代码.

2) Your ping method might simply be crashing if the website is dead. You can show us the code of that method.

4)Thread类很不错,因为您可以使用

4)Thread class is nice because you can easily check the thread state, as per your requirements, using the ThreadState property - just create a List<Thread> , put your threads in it, and then start them one by one.

3)如果要从输入中加载线程数并平均分配工作,请将任务放入队列(可以使用已经建议的ConcurrentQueue),并让线程从队列中加载URL. .示例代码:

3)If you want to load the number of threads from input and distribute the work evenly, put the tasks in a queue (you can use the ConcurrentQueue that has already been suggested) and have the threads load the URLs from the queue. Sample code:

您初始化所有内容

void initialize(){
ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
foreach(string url in websites)
{
    queue.Enqueue(url);
}
//and the threads
List<Thread> threads = new List<Thread>();
for (int i = 0; i < threadCountFromTheUser; i++)
{
    threads.Add(new Thread(work));
}}

//work method
void work()
{
    while (!queue.IsEmpty)
    {
        string url;
        bool fetchedUrl = queue.TryDequeue(out url);
        if (fetchedUrl)
            ping(url);
    }
}

然后运行

foreach (Thread t in threads)
{
    t.Start();
}

代码未经测试

这篇关于C#线程问题和最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆