如何创建循环百分比(处理)[c#] [英] How to create percentage of loop(processing) [c#]

查看:66
本文介绍了如何创建循环百分比(处理)[c#]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:做某事9999次(可能超过)

example : doing something 9999 time (maybe more than)

for (int i = 1; i <= 9999; i++)
{
    // do something
    label1.content = 100*i/9999 + "%" ;
}

,我想在编译时在label1上显示循环的百分比,我几毫秒都无法执行任何操作,而我的标签仅显示100%.先生,有人有主意吗?谢谢.

and I want to show percentage of loop on label1 when I compile I can't doing anything several a millisecond and my label show 100% only. someone have any idea sir? thank you.

推荐答案

您不能在同一线程上运行循环并同时更新UI.这就是为什么您应该始终在后台线程上执行任何长时间运行的工作,并使用分派器定期更新UI的原因.

You can't run a loop on and the update the UI on the same thread simultaneously. That's why you should always perform any long-running work on a background thread and update UI at regular intervals using the dispatcher.

在后台线程上运行某些代码的最简单方法是使用任务并行库(TPL)启动新任务:

The easiest way to run some code on a background thread is to use the task parallel library (TPL) to start a new task:

Task.Run(()=> 
        {
            for (int i = 1; i <= 9999; i++)
            {
                System.Threading.Thread.Sleep(1500); //simulate long-running operation by sleeping for 1.5s seconds... 
                label1.Dispatcher.BeginInvoke(new Action(() => label1.Content = 100 * i / 9999 + "%"));
            }
        });

我的消息框在百分比运行时立即在运行命令后显示消息

my message box immediately show message after i run command while percentage is running

如前所述,该任务正在另一个线程上执行.因此它将与UI线程在 parallel 中运行.这就是循环运行时可以更新UI的原因.

As mentioned the Task is being executed on another thread. So it will run in parallel with the UI thread. That's the reason why the UI can be updated while the loop is running.

任务完成后,可以使用Task.ContinueWith方法显示MessageBox:

You could use the Task.ContinueWith method to show the MessageBox after the task has completed:

int i = 1;
Task.Run(() =>
            {
                for (; i <= 9999; i++)
                {
                    System.Threading.Thread.Sleep(1500); //simulate long-running operation by sleeping for 1.5s seconds... 
                    label1.Dispatcher.BeginInvoke(new Action(() => label1.Content = (i / 9999) * 100 + "%"));
                }
            }).ContinueWith(t =>
            {
              MessageBox.Show("done..." + i.ToString());
            }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

这篇关于如何创建循环百分比(处理)[c#]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆