首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

如何判断子线程是否执行完毕

2012-05-30 
怎么判断子线程是否执行完毕.在程序中,我开启了10个线程,我想在规定时间后去检查 还剩余几个线程未执行.怎

怎么判断子线程是否执行完毕.
在程序中,我开启了10个线程,我想在规定时间后去检查 还剩余几个线程未执行.

怎么做?
上代码,哈哈,谢谢了

[解决办法]
四、使用IAsyncResult asyncResult属性来判断异步调用是否完成

虽然上面的方法可以很好地实现异步调用,但是当调用EndInvoke方法获得调用结果时,整个程序就象死了一样,这样做用户的感觉并不会太好,因此,我们可以使用asyncResult来判断异步调用是否完成,并显示一些提示信息。这样做可以增加用户体验。代码如下:

static void Main(string[] args) 
 { NewTaskDelegate task = newTask; 
IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); 
while (!asyncResult.IsCompleted)
{
Console.Write("*");
Thread.Sleep(100);
} // 由于异步调用已经完成,因此, EndInvoke会立刻返回结果 
int result = task.EndInvoke(asyncResult); 
Console.WriteLine(result); }
[解决办法]

C# code
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Data.SqlClient;using System.Data;namespace ConApp{    class Program    {        static void Main(string[] args)        {            for (int index = TASKCOUNT; --index >= 0; )            {                ThreadPool.QueueUserWorkItem(Run,index);                Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(100, 500));            }            wait.WaitOne();            Console.WriteLine("任意键结束....");            Console.ReadKey();                  }        static ManualResetEvent wait = new ManualResetEvent(false);        static int TASKCOUNT = 100;        static void Run(object obj)        {            Thread.CurrentThread.Name = obj.ToString();            Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(4000, 5000));            if (Interlocked.Decrement(ref TASKCOUNT) == 0)            {                wait.Set();            }            else            {                Console.WriteLine("完成{0}", obj);            }        }    }   }
[解决办法]
C# code
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Data.SqlClient;using System.Data;namespace ConApp{    class Program    {        static void Main(string[] args)        {            for (int index = TASKCOUNT; --index >= 0; )            {                ThreadPool.QueueUserWorkItem(Run, index);                Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(100, 500));            }            wait.WaitOne();            Console.WriteLine("任意键结束....");            Console.ReadKey();        }        static ManualResetEvent wait = new ManualResetEvent(false);        static int TASKCOUNT = 100;        static void Run(object obj)        {            Thread.CurrentThread.Name = obj.ToString();            Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(4000, 5000));            if (Interlocked.Decrement(ref TASKCOUNT) == 0)            {                wait.Set();            }            else            {                Console.WriteLine("还有{0}个未完成", TASKCOUNT);            }        }    }} 

热点排行