如何停止在另一个线程中创建的循环

时间:2018-08-11 20:22:46

标签: c#

我在下面的循环中制作了一个图像记录器,但是我不知道如何停止记录。这是我的代码

void Capture()
{
    while (true)
    {
        Bitmap bm= new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        Graphics g = Graphics.FromImage(bm);
        g.CopyFromScreen(0, 0, 0, 0, bm.Size);
        pictureBox1.Image = bm;
        Thread.Sleep(300);
    }
}

private void btnRecord_Click(object sender, EventArgs e)
{
    Thread t = new Thread(Capture);
    t.Start();
}

请帮助我!

1 个答案:

答案 0 :(得分:3)

由于循环,您有一种非常简单的方法:将标志设置为停止请求:

private volatile bool reqToStopRec = false;

void Capture()
{
    while (!reqToStopRec)
    {
        Bitmap bm= new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        Graphics g = Graphics.FromImage(bm);
        g.CopyFromScreen(0, 0, 0, 0, bm.Size);
        pictureBox1.Image = bm;
        Thread.Sleep(300);
    }
    reqToStopRec = false;
}

private void btnRecord_Click(object sender, EventArgs e)
{
    Thread t = new Thread(Capture);
    t.Start();
}

private void btnStop_Click(object sender, EventArgs e)
{
    reqToStopRec = true;
}

In C# bool writes and reads are atomic,所以您只需要volatile