Parallel.Invoke是只执行第一种方法

编程入门 行业动态 更新时间:2024-10-28 18:22:42
本文介绍了Parallel.Invoke是只执行第一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试过这个

Parallel.Invoke(() => Method1(), () => Method2());

开始的方法1 &安培; 方法2 在同一时间actioning。但方法1 只得到执行。任何解决方案,请。

to start Method1 & Method2 actioning at a same time. But Method1 only is getting executing. Any solution please.

在延续这,我在下面加$ C $角

In continuation to this, I've added below code.

class Program { static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); Task.Factory.StartNew(() => { Thread.Sleep(5000); cts.Cancel(); }); ProcessFiles(cts.Token); Console.ReadKey(); } public static void ProcessFiles(CancellationToken cts) { try { LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(2); List<Task> tasks = new List<Task>(); TaskFactory factory = new TaskFactory(lcts); Parallel.Invoke( () => Method1(cts, tasks, factory), () => Method2(cts, tasks, factory)); Task.WaitAll(tasks.Where(t => t != null).ToArray()); Console.WriteLine("\n\nSuccessful completion."); Console.ReadLine(); } catch (AggregateException aex) { // Ignore } catch (Exception ex) { Console.WriteLine(ex.Message); } } private static void Method1(CancellationToken cts, List<Task> tasks, TaskFactory factory) { for (int i = 0; i < 1000; i++) { int i1 = i; var t = factory.StartNew(() => { Console.WriteLine("Method 1 --- {0} --- {1}", i1, GetGuid()); }, cts); tasks.Add(t); } } private static void Method2(CancellationToken cts, List<Task> tasks, TaskFactory factory) { for (int i = 0; i < 1000; i++) { int i1 = i; var t = factory.StartNew(() => { Console.WriteLine("Method 2 --- {0} --- {1}", i1, GetGuid()); }, cts); tasks.Add(t); } } private static Guid GetGuid() { Thread.Sleep(TimeSpan.FromSeconds(1)); return Guid.NewGuid(); } }

O / P:方法一,只有在调用。方法二是没有的。

O/P: Only Method1 is invoking. Method2 is not.

推荐答案

我可以看到这两种方法都将Console.WriteLines后factory.StartNew前右()执行(Thread.sleep代码()或)。

I can see both methods are executing after adding Console.WriteLines (or Thread.Sleep()) right before factory.StartNew().

罗布感谢为解决方案

更多推荐

Parallel.Invoke是只执行第一种方法

本文发布于:2023-05-29 23:14:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355180.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:种方法   Parallel   Invoke

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!