C#中的线程查询 [英] Threading query in C#

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

问题描述

大家好,

我已经写了一篇关于线程的文章.我正在开发一个用于从邮件服务器提取邮件的应用程序.

该应用程序将不停地运行24/7.我正在使用计时器控件,并且每5分钟触发timer1_tick event并调用两个线程.

每个线程在做什么,就是在调用connectpara.每个线程包含一组用户.线程被调用后,它将为该用户获取邮件.

Hi all,

I already did a post about threads. I am developing an application to fetch mails from the mail server.

The application will be running 24/7 without stopping. I am using a timer control and every 5 minutes the timer1_tick event is fired and the two threads are called.

What each thread is doing is that it is calling a connectpara. Each thread contains a set of users. Once the thread is called, it will fetch mails for that users.

private void timer1_Tick(object sender, EventArgs e)
{
   Thread t = new Thread(connectPara);
   t.Start("sp_users1");
   textBox1.Text = t.ThreadState.ToString();           
   Thread t1 = new Thread(connectPara);
   t1.Start("sp_users2");
   textBox2.Text = t1.ThreadState.ToString();
}



我是第一次使用该线程,我的疑问是:

在这种情况下,如果每个线程都执行了,我怎么知道该线程已经完成了工作?

如果完成,是否需要像处理对象一样中止或处置线程.

请帮助我解决这个问题.

谢谢&问候



I am using the thread for the first time and my doubt is:

In this context, if each thread is executed, how do I know that the thread has finished the job?

If finished, do I need to abort or dispose the thread just like we do for objects.

Kindly help me to resolve this.

Thanks & regards

推荐答案

写道:​​

我怎么知道线程已经完成了工作?

How do i know that the thread has finished the job?



正如我之前所说,您可以调用Thread.IsAliveThread.ThreadState(这将提供更多信息).




As I said before, you can call Thread.IsAlive or Thread.ThreadState ( which gives more information ).


写道:​​

我是否需要像处理对象一样中止或处置线程?

Do i need to abort or dispose the thread just like we do for objects?



Thread没有实现IDisposable,因此您无法处理它.

Thread.Abort邪恶-永远不要使用它!

因此,您的问题的答案是否定的.线程完成后,只需删除对其的所有引用,运行时将为您清理.



我建议您在控件类中保留对线程的引用,并在计时器触发时检查以前的线程是否已完成.如果它们仍在工作,则返回并等待下一个计时器.如果完成,则可以再次创建新的文件.

Nick



Thread does not implement IDisposable, so you can''t dispose it.

Thread.Abort is evil - never use it!

So the answer to your question is no. When a thread finishes, just remove any references to it and the runtime will clean up for you.



I suggest that you keep references to your threads in your control class and when the timer fires, check to see if the previous threads have completed. If they are still working then just return and wait for the next timer. If they have finished, then you can create new ones again.

Nick


通常的做法和最简单的方法是在线程启动后,为每个新线程循环调用thread.Join().主线程将等待加入"线程完成,然后您可以通知用户.



您还可以通过ManualResetEvent
显式发出线程信号
The common practice and the easiest way is to call thread.Join() for each new thread in cycle after your threads have launched. The main thread will wait for the "joined" threads to be finished and then you can notify a user.



You also can signal threads explicitly via ManualResetEvent


这篇关于C#中的线程查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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