本文介绍了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是只执行第一种方法
发布评论