C# 如何停止BackgroundWorker并退出所有我的循环

C# 如何停止BackgroundWorker并退出所有我的循环,c#,winforms,C#,Winforms,我有一个应用程序,它使用BackgroundWorker播放列表中的文件。按下停止按钮后,正在运行的文件将停止运行,但不会停止播放列表中的下一个文件 代码中的变量为: playCount—我运行了多少个文件,numberOfLoops—我要运行多少个循环,循环表示列表框(listBoxFiles)中的所有文件,myClass.playCapture—后台运行的内容 while (playCount < numberOfLoops && bContinuePlay &

我有一个应用程序,它使用BackgroundWorker播放列表中的文件。按下停止按钮后,正在运行的文件将停止运行,但不会停止播放列表中的下一个文件

代码中的变量为: playCount—我运行了多少个文件,numberOfLoops—我要运行多少个循环,循环表示列表框(listBoxFiles)中的所有文件,myClass.playCapture—后台运行的内容

while (playCount < numberOfLoops && bContinuePlay && ifContinue) //play the file
{
    for (int i = 0; (i < listBoxFiles.Items.Count) && bContinuePlay && ifContinue; i++)
    {
        string path = (string)listBoxFiles.Items[i];
        myClass = new myClass(path, playSpeed);
        myClass.evePacketProgress += new myClass.dlgPacketProgress(
            (progressCount) =>
            {
                myClass._fileSelectedIndex = i;
                bgWoSingle.ReportProgress(progressCount, myClass);
            });

        if (selectedAdapter != null)
        {
            bContinuePlay = myClass.playCapture(selectedAdapter._packetDevice); //here the BackgroundWorker running
        }
    }

    playCount++;
}
while(playCount
{
myClass.\u fileSelectedIndex=i;
bgWoSingle.ReportProgress(progressCount,myClass);
});
如果(selectedAdapter!=null)
{
bContinuePlay=myClass.playCapture(selectedAdapter.\u packetDevice);//这里是正在运行的BackgroundWorker
}
}
playCount++;
}

我相信您只需要使用

看起来您可能忘记在停止代码中设置bContinuePlay或ifContinue为false。如果不是这样,请提供更多代码。(启动和停止流程的位置)

我仍然建议从我的回答中查看CancelAsync方法,因为这可能会清理一些代码。调用CancelAsync方法时,它将删除正在运行的BackgroundWorker?那么在取消后应该打开的所有其他文件呢?@user1269592,这是否解决了问题,还是仍然不起作用?