2017-12-12 3 views
0

천천히 화면에 텍스트를 쓰려고합니다. 스페이스 바를 누르고 있으면 텍스트가 더 빨리 나타납니다. 다시 놓으면 같은 속도로 되돌아갑니다. 다른 스레드없이 이렇게비동기 작업을 사용하여 데이터를 즉시 수정할 수 있습니까?

//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 밀리 초가 지나면 텍스트는 코드가 변경되지 않고 종료 될 때까지 속도가 향상됩니다.

답변

0

단추를 button1 및 타이머 timer1과 함께 winforms 응용 프로그램에 넣는 것만으로도 효과가있는 것 같습니다. 폼의 KeyPreview 속성을 true으로 설정해야했습니다.

public partial class Form1 : Form 
{ 
    int _position = 0; 
    string _text = string.Empty; 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if (!timer1.Enabled) 
      DisplayText(@"//Displays text at a certain speed test..."); 
    } 

    //Displays text at a certain speed 
    public void DisplayText(string text, int speed = 200, Color color = default(Color), bool newLine = false) 
    { 
     _position = 0; 
     _text = text; 
     timer1.Interval = speed; 

     timer1.Enabled = true; 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (_position < _text.Length) 
      Debug.Write(_text[_position]); 
     else 
      timer1.Enabled = false; 
     _position++; 
    } 

    private void Form1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.Space) 
      timer1.Interval = 15; 
    } 

    private void Form1_KeyUp(object sender, KeyEventArgs e) 
    { 
     timer1.Interval = 200; 
    } 
} 

나는 이것이 당신이 무엇을하고 있는지 약간 다릅니다 알고,하지만 난 당신이 요점을 얻을 수 있기를 바랍니다. 나는 명확성을 위해 (텍스트의 색을 변경하는 것처럼) 텍스트 쓰기와 관련이없는 모든 코드를 제거했다.

관련 문제