C# - 并行运行两个任务

时间:2017-05-18 08:59:35

标签: c# parallel-processing async-await

我想要并行运行两个任务,目标是:在倒计时时,我想要锁定输入。当计数器为0时,程序应停止锁定输入。到目前为止,我知道如何阻止输入一段时间,但同时我想要有计时器,它将告诉我需要多长时间。这是我的代码:

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        private static TimeSpan timeSpan = new TimeSpan(0, 5, 0);

        static void Main(string[] args)
        {
            Program program = new Program();

            while (timeSpan > TimeSpan.Zero)
            {
                program.timer();
                //Program.BlockInput(timeSpan);
            }

            Console.ReadLine();
        }

        private void timer()
        {
            timeSpan -= new TimeSpan(0, 0, 1);
            Console.WriteLine(timeSpan.ToString());
        }

        private partial class NativeMethods
        {
            [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "BlockInput")]
            [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
            public static extern bool BlockInput([System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)] bool fBlockIt);
        }

        private static void BlockInput(TimeSpan span)
        {
            try
            {
                NativeMethods.BlockInput(true);
                Thread.Sleep(span);
            }
            finally
            {
                NativeMethods.BlockInput(false);
            }
        }

    }
}

2 个答案:

答案 0 :(得分:1)

比线程更好的是使用async / await。将在线程池上运行以下任务。您不需要专门的线程来解决此问题。

    private static async Task BlockInput(TimeSpan span)
    {
        return Task.Run(()=>{
            try
            {
                NativeMethods.BlockInput(true);
                await Task.Delay(span);
            }
            finally
            {
                NativeMethods.BlockInput(false);
            }

        });


    }

答案 1 :(得分:0)

您可以使用另一个线程。 您的计数器正在计数并且输入被阻止,而您可以执行任何其他操作,因为这些操作位于另一个线程上。

public void RunTwoThingsAtOnce()
{
    new Thread( () =>
    {
        while (timeSpan > TimeSpan.Zero)
        {
            program.timer();
            //Input Block
        }

     }).Start();

}