开始,暂停,停止和逐步浏览C#中的集合

时间:2019-06-12 14:23:45

标签: c# .net

我收集了一些单词,希望在一些事件的帮助下进行迭代。理想情况下,单击按钮时,我希望系统开始处理单词列表,但是与此同时,我也希望能够灵活地暂停列表的处理,并通过另一个按钮单击事件手动逐个遍历列表

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            //This event should start/resume processing the list
        }

        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            //This event should terminate processing the list
        }

        private void Pause_Click(object sender, RoutedEventArgs e)
        {
            //This event should pause the processing of list
        }

        private void Step_Click(object sender, RoutedEventArgs e)
        {
            //This event should enable the end user to iterate through the 
            //loop one word at a time by pausing auto processing.
        }

        void ProcessTheWords()
        {
            foreach (var word in listOfWords)
            {
                //process each word
                Thread.Sleep(100);
            }
        }

1 个答案:

答案 0 :(得分:-1)

感谢大家的回应。 我可以借助任务和取消令牌来获得所需的输出。

内联是该实现的代码段

        int counterValue = 0;
        CancellationTokenSource cts;
        static readonly object obj = new object();
        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            cts = new CancellationTokenSource();
            await Task.Run(() => ProcessTheWords(false), cts.Token);
        }

        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
            counterValue = 0;
        }

        private void Pause_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
        }

        private async void Step_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
            await Task.Run(() => ProcessTheWords(true));
        }

        void ProcessTheWords(bool executeOnce)
        {
            lock (obj)
            {
                for (int i = counterValue; i < listOfWords.Count; i++)
                {
                    // process the current word by fetching it from the list: 
                    // listOfWords[counterValue];
                    Thread.Sleep(1000);
                    counterValue++;
                    if (cts.IsCancellationRequested || executeOnce)
                        break;
                }
            }
        }