如何使用第二个线程终止主线程? [英] How to use second thread to abort primary thread?

查看:108
本文介绍了如何使用第二个线程终止主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个密码验证功能,我想在第二个线程中使用此功能来检查密码.如果密码正确,则第二个线程退出.否则,两个线程都退出.而且主线程可以随时提示第二个线程检查密码.

我的解决方案是:创建第二个线程,使用ThreadStart.(verifyfunction)验证密码,但是我发现我无法当我输入错误的密码时中止这两个线程.怎么做 ?实现是在主线程还是第二线程中?我的目的是使用第二个线程来验证密码,这样才不会影响主线程.(验证密码会花费很多时间.在验证时,主线程会做自己的工作.

谢谢!

I have a password verify function for example, I want use this function in second thread to check the password. If the password is correct, second thread exit. Otherwise, the two thread are all exit. And the primary thread can prompts the second thread to check password at any moment.

My solution is: creat a second thread, use ThreadStart.(verifyfunction) to verify password, but I find I can't abort these two thread when I get the wrong password. How to do it ?  Is implemention  in primary thread or second thread?  My purpose is using second thread to verify password so it do not affect the primary thread.(verifying the password  takes to much time. When it verifying, the primary thread do its own work.

Thank you!

推荐答案

据我了解,您的辅助线程的目的只是为了验证密码.

我假设您正在WinForm中使用它.在这种情况下,一种好的方法是使用backgroundworker线程.您可以将所需的输入传递给DoWork事件处理程序,然后将结果(成功或失败)分配给DoWorkEventArgs的Result属性.现在在RunWorkerCompleted事件中进行检查.有关如何使用BackgroundWorker类的详细说明,请参见下面的msdn链接

http://msdn.microso ft.com/zh-CN/library/system.componentmodel.backgroundworker.aspx
As I understand the purpose of your secondary thread is only to verify the password. You did not mention how it will intimate the primary thread of the result. Is it through some shared variable?

I assume that you are using this from a WinForm. A good approach in this case would be to use a backgroundworker thread. You can pass in the required inputs to the DoWork event handler and assign the result (success or failure) to the Result property of DoWorkEventArgs. Now examine this in the RunWorkerCompleted event. For a detailed explanation of how to use the BackgroundWorker class see the below msdn link

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx


这篇关于如何使用第二个线程终止主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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