0

我有以下代码,IlegalOperationException因为我的参数拥有另一个线程。我知道为什么会出现此异常,但我不知道如何解决此问题。

//called on UI thread
public void redraw()
{
     new Thread(setPoints).Start(); //calculating new points
}

void setPoints()
{
    PointCollection c = new PointCollection();
    //calculating points to collection
    Task.Factory.StartNew((Action<object>)((p) => { polyline.Points = (PointCollection)p; }), c);

}

编辑:

好的,这里与调度员一致

polyline.Dispatcher.Invoke((Action<PointCollection>)((p) => { polyline.Points = p; }), c);
4

2 回答 2

2

PointCollection 是一个 DependencyObject,您不能从一个线程实例化它并从另一个线程访问它。尝试在单独的线程中进行计算以生成所需的任何数据,然后在 UI 线程中实例化 PointCollection。

于 2013-01-07T00:21:07.480 回答
1

我想你需要做这样的事情

private void reDraw()
        {
             Task<IList<Point>> calculatePointTask = Task.Factory.StartNew(() =>
            {
                //Use the list of points instead of thread-bound PointCollection
                IList<Point> pointCollection = new List<Point>();

                //Simulating that we calculate points
                Thread.Sleep(3000);

                pointCollection.Add(new Point(10,20));
                pointCollection.Add(new Point(10,20));

                return pointCollection;
            });

        calculatePointTask.ContinueWith(ante =>
            {


                var calculatedPoints = calculatePointTask.Result;

                Action<IList<Point>> updateUI = (points) =>
                    {

                        var pointCollection = new PointCollection(points);
                        polyline.Points = pointCollection;

                    };

                Application.Current.Dispatcher.Invoke(updateUI, calculatedPoints);



            }, TaskContinuationOptions.AttachedToParent);
        }

在您的重绘功能中。

编辑:计算点时使用点列表而不是 PointCollection 实例

于 2013-01-07T00:07:52.203 回答