C#中的主线程和子线程之间存在多线程问题. [英] Multi Threading problem between Main and Child thread in C#.

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

问题描述

我有一个主线程,所有主线程和子线程都分配了4个子线程,问题是主线程快速完成工作,但子线程无法完成.如果主线程在子线程之前快速完成,程序将挂起-上.我需要运行主线程,直到子线程完成工作为止.

I have a main thread , 4 child thread work is assigned to all main and child threads, the problem is that main thread finishes the work fast, but child threads cannot.If main thread finishes fast before child thread the program hangs-on. I need to run the main thread until the child threads finish the work.

推荐答案

有很多方法可以做到这一点,对我而言,最简单的方法是使用join .

示例代码

There is many ways to do this and as per me the simplest way is to use join.

Sample Code

for(int i = 0 ;i < childThreadList.Count; i++) 
{     
      childThreadList[i].Join(); 
} 
///...The following code will execute when all threads in the list have been terminated.../// 


首先,没有诸如子线程和父线程的概念.我明白问题所在.有很多同步线程的方法,但是您的情况几乎是最简单的:一个线程可以进入等待状态,直到其他线程通过System.Windows.Thread.Join完成.例如,如果线程th1调用th2.Join(其中th2是另一个当前活动的线程),则线程th1将进入等待状态:它已被操作系统关闭,没有计划返回到在一定条件下执行(因此,将CPU时间完全花费为零),直到OS唤醒为止.在这种情况下,th2完成后将唤醒线程th1.另一个条件包括th1.Abortth1.Interrupt或先前调用的th2.Join的超时(它通过timeout参数调用).

在这种情况下,这正是您所需要的.您的启动线程应依次为其他四个线程调用Thread.Join四次;调用的顺序无关紧要:如果线程已经完成,则Thread.Join会立即立即返回.如果您考虑这些操作的顺序,您会发现它始终可以工作……只要您以某种方式保证四个线程中的每一个都一定可以完成.

问题解决了.

—SA
First, there is no such notion as child and parent threads. I understand the problems though. There are many way to synchronize threads, but your case is nearly the simplest: one thread can get into a wait state until some other thread finished via System.Windows.Thread.Join. For example, is a thread th1 calls th2.Join (where th2 is another currently active thread), the thread th1 will enter the wait state: it''s switched off by OS and does not scheduled back to execution (thus spending exactly zero CPU time) until OS awakes is on certain condition. In this case, the thread th1 will be waken up when th2 finished. Another conditions include th1.Abort, th1.Interrupt or timeout on the previously called th2.Join (it it was called with timeout parameter).

This is exactly what you need in this case. You start-up thread should call Thread.Join four times for other four threads, sequentially; the order of calls does not matter: if a thread is already finished, Thread.Join will simply return immediately. If you think about the order of these operations you will see it always works… provided you somehow guarantee that each of four thread will certainly finish.

Problem solved.

—SA


这篇关于C#中的主线程和子线程之间存在多线程问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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