CSkin博客

标题: C#中while循环和线程问题 [打印本页]

作者: yuzhuo83    时间: 2016-10-11 15:51
标题: C#中while循环和线程问题
public bool bool1;
        private void button4_Click(object sender, EventArgs e)
        {
            bool1 = true;
            Thread three1 = new Thread(test);
            three1.Start();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            bool1 = false;
            Thread three1 = new Thread(test);
            three1.Abort();
            //关闭资源
        }

        public void test()
        {
            while (bool1)
            {
                //资源使用

            }
        }


上面的例子,我点击第一个按钮,线程启动,进入一个while循环,循环里用到一个打开的资源,比如相机了,数据库了等等,
现在我点击第二个按钮,将循环的判断设为false,然后关闭线程,关闭资源。

问题是,点击第二个按钮的时候,有时候循环里正在使用的资源会报错,我觉得是点击第二个按钮时,正好在循环里,还没到使用资源的时候,第二个按钮执行完毕,资源关闭了,但是正好循环到使用资源的语句,然后就报错了,怎么避免这种错误的发生,前辈们帮帮忙解答一下,万分感谢!!!


作者: 九日    时间: 2016-10-11 17:44
我的哥这是两个不同的线程了
作者: aisht    时间: 2016-10-11 20:45
你的例子中.
bool1 是全局变量

和线程无关.
你只要点击button5  ,执行到bool1 = false; 这句的时候.
test()中就会不再循环.  和 哪个线程无关.


作者: 乔克斯    时间: 2016-10-12 09:42
[C#] 纯文本查看 复制代码
public bool bool1;
public Thread three1;
private void button4_Click(object sender, EventArgs e) {
    bool1 = true;
    three1 = new Thread(test);
    three1.Start();
}

private void button5_Click(object sender, EventArgs e) {
    try {
        bool1 = false;
        three1.Abort();
        //关闭资源
    } catch (Exception ex) { }
}

public void test() {
    while (bool1) {
        //资源使用

    }
}





欢迎光临 CSkin博客 (http://bbs.cskin.net/) Powered by Discuz! X3.2