Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按字符/计时器打印字符串字符_C#_Printing_Timer - Fatal编程技术网

C# 按字符/计时器打印字符串字符

C# 按字符/计时器打印字符串字符,c#,printing,timer,C#,Printing,Timer,我正在制作一个基于文本的游戏,我想用文本打印的方式慢慢地制作一个介绍(一个字符一个字符,相差约100毫秒)。我试着制作一个循环,循环字符串,一个一个地打印字符,但我需要一个计时器,即使在谷歌的帮助下,我也无法实现这一点。所以我需要一个定时器或其他算法的帮助,以便缓慢地打印字符串。 我的代码: static void PrintSlowly(string print) { foreach(char l in print) { Console.Write(l);

我正在制作一个基于文本的游戏,我想用文本打印的方式慢慢地制作一个介绍(一个字符一个字符,相差约100毫秒)。我试着制作一个循环,循环字符串,一个一个地打印字符,但我需要一个计时器,即使在谷歌的帮助下,我也无法实现这一点。所以我需要一个定时器或其他算法的帮助,以便缓慢地打印字符串。 我的代码:

static void PrintSlowly(string print)
{
    foreach(char l in print) {
        Console.Write(l);
        //timer here
    }
    Console.Write("\n");
}

讨厌的、讨厌的廉价解决方案:

static void PrintSlowly(string print)
{
    foreach(char l in print) {
        Console.Write(l);
        Thread.sleep(10); // sleep for 10 milliseconds    
    }
    Console.Write("\n");
}

因为您可能不太关心性能,所以可以这样做。但是请记住,基于apomene的解决方案,我会选择(真实的)基于计时器的解决方案,因为
Thread.Sleep
非常不精确

static void PrintSlowly(string print)
{
    int index = 0;
    System.Timers.Timer timer = new System.Timers.Timer();

    timer.Interval = 100;
    timer.Elapsed += new System.Timers.ElapsedEventHandler((sender, args) =>
    {
        if (index < print.Length)
        {
            Console.Write(print[index]);
            index++;
        }
        else
        {
            Console.Write("\n");
            timer.Enabled = false;
        }
    });

    timer.Enabled = true;
}

它使用等待,以便其他应用程序/线程可以使用处理器

也许睡100毫秒?你的游戏是多线程的吗?
Thread.Sleep(100)
?@bali182你会在学习的时候制作一个多线程的游戏软件吗?@PatrikEckebrecht不太理想。但是你可能会这样做。但是对于这个问题有简单的解决方案,没有对线程的深入理解。看我的答案。毫秒,就像它后面的评论所说的那样。为什么线程这么糟糕?没有真正理解线程(我不得不)线程并不可怕。一旦您了解了并发线程及其同步的概念,您就有了一个强大的工具来实现解决方案。但这是一个对初学者不友好的主题。@Ravid
Thread.Sleep
会使当前线程等待特定的毫秒数,然后再继续。运行的每个程序都至少有一个线程。如果在程序的主线程上调用
Thread.Sleep
,并且只有一个线程,则意味着当线程处于睡眠状态时,不会发生任何事情。
static System.Timers.Timer delay = new System.Timers.Timer();
static AutoResetEvent reset = new AutoResetEvent(false);

private static void InitTimer()
{
    delay.Interval = 100;
    delay.Elapsed += OnTimedEvent;
    delay.Enabled = false;
}

private static void OnTimedEvent(object sender, ElapsedEventArgs e)
{
    ((System.Timers.Timer)sender).Enabled = false;
    reset.Set();
}

static void PrintSlowly2(string print)
{
    InitTimer();

    foreach (char l in print)
    {
        Console.Write(l);
        delay.Enabled = true;

        reset.WaitOne();
    }
    Console.Write("\n");
}