テキストを画面にゆっくりと書き込もうとしています。スペースバーを押したままにすると、テキストがより速く表示されます。それが再びリリースされると、同じ速度に戻ります。別のスレッドせずにこれを行う非同期タスクを使用してオンザフライでデータを変更するにはどうすればよいですか?
//Displays text at a certain speed
public async void DisplayText(string text, Speed speed = Speed.medium, ConsoleColor color = ConsoleColor.White, bool newLine = false)
{
completed = false;
//Defines color and speed
Console.ForegroundColor = color;
scrollSpeed = DefineSpeed(speed);
var keyCheck = Task.Run(() => CheckSpeedUp());
foreach (char c in text)
{
//If the asynchronous background method has detected the spacebar is pressed...
//Speed the text up, otherwise put it back to default.
if (speedUp)
scrollSpeed = 15;
else
scrollSpeed = 200;
Console.Write(c);
System.Threading.Thread.Sleep(scrollSpeed);
}
//Display has finished
completed = true;
//If there is a new line, write it
if (newLine)
Console.WriteLine();
//Set the text color back to white
Console.ForegroundColor = ConsoleColor.White;
}
は、それが遅くなるだろうというとき、テキストがスピードアップ開始となりときの間の遅延の多くが生じました。 私はこれを、自分のスレッドで処理するタスクを作成することで解決しようとしました。そうすれば、メインコードはブーリアン「speedUp」について心配するだけです。
//Asynchronous task to check if the spacebar is pressed and set the speedUp bool
private async Task CheckSpeedUp()
{
while(!completed)
{
if (Program.IsKeyDown(ConsoleKey.Spacebar))
{
speedUp = true;
}
else
{
speedUp = false;
}
}
}
私は、このシステムは、foreachループはそのテキストを表示する速度をスピードアップし、スペースキーが解放されたときに再びそれを遅らせるだろうと思いました。
しかし、スペースバーが押された(またはタップされていても)約500ミリ秒後に、テキストはコードが変更されずに終了するまでスピードアップします。