调度员.调用参数抛出IlegalOperationException

本文关键字:IlegalOperationException 参数 调用 调度员 | 更新日期: 2023-09-27 17:50:48

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

好的,这是dispatcher

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

调度员.调用参数抛出IlegalOperationException

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

我猜你需要这样做

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实例

相关文章:
  • 没有找到相关文章