c# - 中止线程(Backgroundworker)..需要建议

标签 c# winforms multithreading backgroundworker

        public void ReplayGame()
    {

        if (Class2.replayIsOn)
        {

            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }                 
    }

我想在函数结束后立即取消/停止 backgroundwoker1.. backgroundworker 事件运行几秒钟然后停止..当它停止时我希望它结束​​!!..

我怎样才能完成那个任务/?没有得到我现在得到的任何无效操作异常

更新:

    public void ReplayGame()
    {

        if (Class2.replayIsOn)
        {
            replay = serializeMeh.giveBackDictionary();
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.RunWorkerAsync();
        }        
    }



    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        int[] makeSelfMoves = new int[4];
        if (!backgroundWorker1.CancellationPending)
        {
            lock (replay)
            {
                foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
                {
                    if (backgroundWorker1.CancellationPending)
                    {
                        break;
                    }
                    makeSelfMoves = replay[item.Key];
                    codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
                    PrintPieces(codeFile.PieceState()); Invalid operation exception is thrown here when chess pieces are drawn on the screen ... Two threads enter the loop simultaneously..:(...Invalid operation exception


                    System.Threading.Thread.Sleep(1000);
                }
                Class2.counter = serializeMeh.serializedCounter;
                Class2.replayIsOn = false;
                Game.WasntSerialized = true;
            }
        }
        backgroundWorker1.CancelAsync();
    }

最佳答案

您是否检查过工作人员是否支持取消?

backgroundWorker1.WorkerSupportsCancellation = true;

如果你没有显式设置它而你调用

backgroundWorker1.CancelAsync();

InvalidOperationException 将被抛出,因为默认情况下 worker 不支持异步取消。

更新
这只是检查工作人员状态的属性,如果您需要取消您需要调用的工作 backgroundWorker1.CancelAsync();

查看示例 here

关于c# - 中止线程(Backgroundworker)..需要建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6779243/

相关文章:

c# - 过滤数据绑定(bind)数据 GridView (带有组合框列)的数据 View 使其速度非常慢

c# - 在面板上动态创建按钮

c# - Windows窗体应用程序-缓慢/无响应的UI

c# - 从 Fiddler 隐藏我的应用程序产生的 Http(s) 流量

c# - 如何在 C# 中自动化程序集文件版本

c# - ASP.NET Core 托管在 Windows 服务中 - 未提供静态文件(即/wwwroot 的内容)

c# - 我怎样才能在转发器中做一个 if 语句

c# - 尝试让对话框窗口记住它的最后位置

c++ - 来自 c++11 的 std::thread 问题

Python并发 future executor.submit超时