CodeSnippet/CsharpTests/ParallelTests.cs

(开头部分) 9KB

这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。

namespace CodeSnippet.CsharpTests
{
    using System;
    using System.Collections.Concurrent;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestCategory("Parallel")]
    [TestClass()]
    public class ParallelTests
    {
        [TestMethod]
        public void Parallel_Example_01()
        {
            var watch = Stopwatch.StartNew();
            watch.Start();
            Run1();
            Run2();
            Run3();
            watch.Stop();
            Console.WriteLine("串行开发,总耗时{0}", watch.ElapsedMilliseconds);

            watch.Restart();

            Parallel.Invoke(Run1, Run2, Run3);
            watch.Stop();
            Console.WriteLine("并行开发,总耗时{0}", watch.ElapsedMilliseconds);

            static void Run1()
            {
                Console.WriteLine("Run1,我需要1s");
                Thread.Sleep(1000);
            }
            static void Run2()
            {
                Console.WriteLine("Run2,我需要2s");
                Thread.Sleep(2000);
            }
            static void Run3()
            {
                Console.WriteLine("Run3,我需要3s");
                Thread.Sleep(3000);
            }
            Assert.IsTrue(true);
        }

        [TestMethod]
        public void Parallel_Example_02()
        {
            Console.WriteLine("主线程启动,线程ID:{0}", Thread.CurrentThread.ManagedThreadId);

            Parallel.Invoke(
                () => Run1("task1"),
                () => Run2("task2"),
                () => Run3("task3"));

            Console.WriteLine("主线程结束,线程ID:{0}", Thread.CurrentThread.ManagedThreadId);

后面还有 228 行代码,解锁后查看完整代码

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。