嵌套for循环和使用线程 [英] nested for loop and using threading

查看:435
本文介绍了嵌套for循环和使用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有



首先关于我的应用



i有两个listviewitem有数字值而我想要第一个列表视图中的第一个项目与第二个列表视图中的前5个数字(数字编号),但在此操作之间我希望此操作睡眠1分钟,睡眠时间,第一个列表视图中的第二个数字与第二个

第二列表视图中的5个号码(按号码排列)和........等等



这是我的代码但是不使用线程并仅计算消息框以检查代码是否正常工作



Dear all

First about my app

i have two listviewitem that have numbers value and i want the first item in the first listview sum with the first 5 number in the second listview (number by number)but between this operation i want this operation sleep 1 min and when it sleep , the second number in the first listview sum with the second 5 number in the
second listview (number by number) and ........etc

this is my code but without using threading and calculate only message box to check the code work correctly

private void button3_Click(object sender, EventArgs e)
        {
 int inc = 0;

            for (int i = 0; i < listView1.Items.Count; i++)
            {

                for (int j = 0; j < 5; j++)
                {
                    
                    MessageBox.Show(listView1.Items[j].SubItems[0].Text + "  To  " + listView2.Items[inc].SubItems[0].Text);
                   
                    //i want to sleep the above line 1 min and containu the loop 
                    if (inc >= listView2.Items.Count - 1)
                    {
                        inc = 0;
                    }
                    else
                    {
                        inc++;
                    }


                }

推荐答案

你不想使用Sleep完全 - 这将阻止主UI线程,因此您的应用程序将完全无响应。并且你不能轻易地将你的代码移动到辅助线程,因为你应该只从UI线程访问UI组件 - 否则你会得到一个交叉线程错误。



因此,设置一个Timer,并使用Tick事件围绕循环执行一个循环 - 自己设置循环变量,并在Tick处理程序中执行一个循环。
You don't want to use Sleep at all - that will block the main UI thread, so your application will become completely unresponsive. And you can't easily move your code to a secondary thread as you should only access UI components from the UI thread - or you will get a cross threading error.

So instead, set up a Timer, and use the Tick event to do one cycle round the loop - set the loop variables up yourself, and just "do" one loop in the Tick handler.


这篇关于嵌套for循环和使用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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