[英]C# - run two task parallel
我想並行運行兩個任務,目標是:在進行倒計時的同時,我想鎖定輸入。 當計數器為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);
}
}
}
}
比線程更好的是使用異步/等待。 以下任務將在線程池上運行。 您不需要專用線程來解決此問題。
private static async Task BlockInput(TimeSpan span)
{
return Task.Run(()=>{
try
{
NativeMethods.BlockInput(true);
await Task.Delay(span);
}
finally
{
NativeMethods.BlockInput(false);
}
});
}
您可以僅使用另一個線程。 您的計數器正在計數並且輸入被阻止,但是您可以執行其他任何操作,因為這些操作在另一個線程上。
public void RunTwoThingsAtOnce()
{
new Thread( () =>
{
while (timeSpan > TimeSpan.Zero)
{
program.timer();
//Input Block
}
}).Start();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.