任务无限循环中的字符串意外行为c#

时间:2017-11-26 21:38:46

标签: c# asynchronous task action

Synth类中有一个名为“word”的字符串值,它以奇怪的方式运行。它会在我调试的时候完全改变每个断点迭代,而它应该保持放置直到我按下空格。如果我写“你好”我会得到“他”然后“heo”然后“hll”。我不明白为什么会发生这种情况,因为这个变量不能从其他任何地方访问。发生了什么事?

class Program
{
    static void Main(string[] args)
    {

        Synth synth = Synth.Instance;

        CancellationTokenSource tokenSource = new CancellationTokenSource();
        Task.Run(() => synth.ReadConsole(tokenSource.Token), tokenSource.Token);
        Task.WaitAll(synth.ReadConsole(tokenSource.Token));
    }
}
public sealed class Synth
{
    SpeechSynthesizer synthesizer = new SpeechSynthesizer();
    static readonly Synth _instance = new Synth();
    public static Synth Instance
    {
        get { return _instance; }

    }
    protected Synth()
    {

        text.Add("test");


    }
    public List<string> text = new List<string>();
    public async Task ReadConsole(CancellationToken token)
    {
        string word = "";
        while (true)
        {
            token.ThrowIfCancellationRequested();
            if (Console.KeyAvailable)
            {
                Char key = Console.ReadKey().KeyChar;
                if (key == ' ')
                {
                    text.Add(word);
                    word = "";
                    synthesizer.SpeakAsync(text[text.Count - 1]);

                }
                else
                {
                    word += key.ToString();
                }
            }



        }
    }

0 个答案:

没有答案