Dispatcher.Invoke参数抛出IlegalOperationException

时间:2013-01-06 23:42:45

标签: c# wpf c#-4.0 asynchronous

我有以下代码,我得到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);

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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实例