backgroundworker停止工作,只返回错误

时间:2013-12-16 15:03:30

标签: c# multithreading backgroundworker kinect

我正在用c#编写kinect sdk 1.8的应用程序。我正在使用一种方法来了解handpointer是否悬停在一个接口元素上,这个metod在skeletonframeready中运行。

    public void CheckButton(Shape container, Point target, Point ContainerPoint)
    {
        // this allows our worker to report progress during work
        // bw.WorkerReportsProgress = true;

        bw = new BackgroundWorker();
        bw.WorkerSupportsCancellation = true;
        // what to do in the background thread
        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            _topBoundary = ContainerPoint.Y;
            _bottomBoundary = _topBoundary + container.Height;
            _leftBoundary = ContainerPoint.X;
            _rightBoundary = _leftBoundary + container.Width;

            //use midpoint of item (width or height divided by 2)
            _itemLeft = target.X;
            _itemTop = target.Y;

            if (_itemTop < _topBoundary || _bottomBoundary < _itemTop)
            {
                //Midpoint of target is outside of top or bottom
                args.Result = "no";
            }
            else if (_itemLeft < _leftBoundary || _rightBoundary < _itemLeft)
            {
                //Midpoint of target is outside of left or right
                args.Result = "no";
            }
            else
            {
                args.Result = "yes";
            }
        });

        // what to do when worker completes its task (notify the user)
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            if (args.Error != null)
            {
              // here the app stops
                Console.WriteLine(args.Error.Message);
            }
            else
            {
                // Finally, handle the case where the operation  
                // succeeded.
                if (args.Result.ToString() == "yes")
                {
                   //Hovering
                }
                else
                {
                  //Not hovering
                }
            }
        });
        if (bw.IsBusy != true)
        {
            bw.RunWorkerAsync();
        }
    }

直到几个小时前,这段代码才真正起作用,现在(没有任何修改)代码总是返回错误“调用线程无法访问此对象,因为不同的线程拥有它”。这段代码有什么问题?

修改

这是调用此方法

 CheckButton(Rect, Point, PointLeftTop);

我在主线程中使用Shape调用方法,将handpointer坐标称为poin,并在形状的左上角调用。如果我的handpointer悬停一个确定的形状,我知道这些参数我知道应用程序的循环,就像我作为参数传递的那样。我对此方法的期望是:从主线程调用,在后台线程中调用doww(bw.DoWork),在主线程中返回结果(bw.RunWorkerCompleted)。 代码停在这里:

        if (args.Error != null){
         // here the app stops
           Console.WriteLine(args.Error.Message);
      }

0 个答案:

没有答案