请教个关于线程的问题

x3312756123 2014-03-25 10:52:18
请教个问题, 怎么让两条线程同时运行,并且两条中的任何一条结束两条都结束,这两条线程没有一条是在主函数的,求个范例代码
...全文
118 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
x3312756123 2014-03-27
  • 打赏
  • 举报
回复
刚开始接触c,有些代码看不明白
xingeddx 2014-03-25
  • 打赏
  • 举报
回复
设置一个两个线程都能访问的变量,同时对变量操作,进行判断。 private static bool allreturn = false; private static Thread[] ts = new Thread[2]; static void Main(string[] args) { InitTs(); Console.Read(); } private static void InitTs() { ts[0] = new Thread(new ThreadStart(threadfun1)); ts[1] = new Thread(new ThreadStart(threadfun2)); ts[0].Start(); ts[1].Start(); } private static void threadfun1() { int i = 0; while (true) { Console.WriteLine(AppDomain.GetCurrentThreadId().ToString()); Thread.Sleep(1000); if (i % 2 == 0 || allreturn) { Console.WriteLine(AppDomain.GetCurrentThreadId().ToString() + " 要结束了"); allreturn = true; return; } i++; } } private static void threadfun2() { int i = 0; while (true) { Console.WriteLine(AppDomain.GetCurrentThreadId().ToString()); Thread.Sleep(1000); if (i == 10 || allreturn) { Console.WriteLine(AppDomain.GetCurrentThreadId().ToString()+" 要结束了"); allreturn = true; return; } i++; } }
x3312756123 2014-03-25
  • 打赏
  • 举报
回复
抱歉我没有说清楚,我需要的是c#语言编写的
x3312756123 2014-03-25
  • 打赏
  • 举报
回复
是个菜鸟,我想问一下,这是c#的语言写的吗?
a121984376 2014-03-25
  • 打赏
  • 举报
回复
手写代码,可能有误

static void Main()
{
var source = new CancellationTokenSource();

var token = soure.Token;

//启动第一个线程
var taks1 = Task.Factory.StartNew(()=>{

//执行任务后,发送取消通知.
souce.Cancel();
},token);

//第二个线程启动
var taks2 = Task.Factor.StartNew(()=>{
//执行任务
whie(true)
{
//检测是否发送了取消通知.
if(token.IsCancellationRequedst)
{
//如果被取消,则终止当前线程,抛出异常
 token.ThrowIfCancellationReuqest();
}
}

},token);
}


a121984376 2014-03-25
  • 打赏
  • 举报
回复
引用 2 楼 x3312756123 的回复:
是个菜鸟,我想问一下,这是c#的语言写的吗?
当然是c#写的啊~~~~ 以上代码在.net 4.0中使用~

110,530

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧