천천히 화면에 텍스트를 쓰려고합니다. 스페이스 바를 누르고 있으면 텍스트가 더 빨리 나타납니다. 다시 놓으면 같은 속도로 되돌아갑니다. 다른 스레드없이 이렇게비동기 작업을 사용하여 데이터를 즉시 수정할 수 있습니까?
는//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 밀리 초가 지나면 텍스트는 코드가 변경되지 않고 종료 될 때까지 속도가 향상됩니다.