苦恼几天了,请问如何判断线程结束
这几天在网上找了个天翻地覆
依然没有搞定
因为没有用线程池
所以 WaitHandle 是用不了了
Thread.Join() 也试了一下
程序跑的时候会处于假死静态
小弟新手
折腾C#才几天
希望各位前辈能赏个详细点的例子
跪谢了
public Form1_Load() { for(int i=0;i <10;i++) //创建线程 { Class1 MyClass = new Class1(); Thread t = new Thread(MyClass.MyMethod); t.Start(); } // 我这里想在10个线程都结束后显示这段话 要怎么写?多谢! MessageBox.Show( "All Thread Finished! "); }
System.Threading.Thread t = new System.Threading.Thread(); t.IsAlive
[解决办法]
给你代码:
这是个思路 当然 可能你的项目不一样,但是改下就OK了
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.IO;using Test.Code;using System.Threading;namespace Test{ class Program { public static int Flag = 10; public static bool FinishFlag = false; public static object objLock = new object(); static void Main(string[] args) { TestEventClass tec = new TestEventClass(); tec.TestEvent += new TestEventClass.TestEventHandler(tec_TestEvent); Thread[] threadarray = new Thread[10]; for (int i = 0; i < 10; i++) { threadarray[i] = new Thread(new ParameterizedThreadStart(tec.RaiseEvent)); threadarray[i].Start(i); } while (FinishFlag == false) { Thread.Sleep(100); } Console.WriteLine("线程都执行完毕了"); Console.ReadLine(); } static void tec_TestEvent(object sender, TestEventClass.TestEventArgs e) { /* 做你要做的事 */ lock (objLock) { Flag += 1; if (Flag >= 10) { FinishFlag = true; } } } } public class TestEventClass { //定义事件参数类 public class TestEventArgs : EventArgs { public readonly object KeyToRaiseEvent; public TestEventArgs(object keyToRaiseEvent) { KeyToRaiseEvent = keyToRaiseEvent; } } //定义delegate public delegate void TestEventHandler(object sender, TestEventArgs e); //用event 关键字声明事件对象 public event TestEventHandler TestEvent; //事件触发方法 protected virtual void OnTestEvent(TestEventArgs e) { if (TestEvent != null) TestEvent(this, e); } //引发事件 public void RaiseEvent(object obj) { TestEventArgs e = new TestEventArgs(obj); OnTestEvent(e); } } }
[解决办法]
//任务集合 List<Task> ts = new List<Task>(); //干活 Action<object> action = (object num) => Thread.Sleep((int)num * 1000); //干完活 Action<Task> action1 = (Task t) => Console.WriteLine(t.Id + " finish!"); //所有的活干完了 Action<Task[]> action3 = (Task[] tarr) => Console.WriteLine("all finish!"); //初始化任务,将任务添加进任务集合 for (int i = 1; i < 5; i++) { Task t1 = new Task(action, i); t1.ContinueWith(action1); ts.Add(t1); } //定义任务工厂 TaskFactory tf = new TaskFactory(); tf.ContinueWhenAll(ts.ToArray(), action3, CancellationToken.None); //所有任务开始干活 ts.ForEach(t => { t.Start(); Console.WriteLine(t.Id + " start!"); });
[解决办法]
我之前也遇到这个问题,我是做网络代理测试的,用到多线程异步测试提高效率。
待所有测试IP都测试完成后,应该给个提示全部测试完成,然后界面上按钮状态等啥的变成可用。
我目前是这样做的
1 定义一个类
muiltTimes()
{
public timeCnt;
public TotalCnt;
public Action doAfterAllComplete;
}
2 将该类的对象传递给 MyClass.MyMethod方法
在MyClass.MyMethod 方法中对timeCnt计数递增(一定要先锁定对象lock(obj))
然后判断 timeCnt 是否等于totalCnt如果等于,那么执行委托doAfterAllComplete
(委托 doAfterAllComplete ,以及 timeCnt TotalCnt 是在你启用多线程之前初始化的)
3 对于线程传递参数,想必应该清楚如果不清楚百度一下...