Parallel.Invoke仅执行第一种方法

时间:2015-07-27 05:16:51

标签: c# asp.net multithreading linq

我试过这个

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

开始 Method1 & 方法2 同时执行操作。但 Method1 只是正在执行。请解决任何问题。

继续this后,我添加了以下代码。

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:只有Method1正在调用。方法2不是。

enter image description here

1 个答案:

答案 0 :(得分:0)

我可以看到在factory.StartNew()之前添加Console.WriteLines(或Thread.Sleep())后两个方法都在执行。

感谢Rob提供解决方案