以下是我的場景:用戶單擊一個WPF按鈕,該按鈕啓動地圖上點集合的開放式時段。當用戶點擊「完成收集」按鈕時,我想完成CollectPoints()
任務。使用CancellationToken中斷嵌套任務
這裏是我的SegmentRecorder
類的作品:
private CancellationTokenSource _cancellationToken;
public virtual async void RecordSegment(IRoadSegment segment)
{
_cancellationToken = new CancellationTokenSource();
var token = _cancellationToken.Token;
// await user clicking points on map
await CollectPoints(token);
// update the current segment with the collected shape.
CurrentSegment.Shape = CurrentGeometry as Polyline;
}
// collect an arbitrary number of points and build a polyline.
private async Task CollectPoints(CancellationToken token)
{
var points = new List<MapPoint>();
while (!token.IsCancellationRequested)
{
// wait for a new point.
var point = await CollectPoint();
points.Add(point);
// add point to current polyline
var polylineBuilder = new PolylineBuilder(points, SpatialReferences.Wgs84);
CurrentGeometry = polylineBuilder.ToGeometry();
// draw points
MapService.DrawPoints(CurrentGeometry);
}
}
// collect a point from map click.
protected override Task<MapPoint> CollectPoint()
{
var tcs = new TaskCompletionSource<MapPoint>();
EventHandler<IMapClickedEventArgs> handler = null;
handler = (s, e) =>
{
var mapPoint = e.Geometry as MapPoint;
if (mapPoint != null)
{
tcs.SetResult(new MapPoint(mapPoint.X, mapPoint.Y, SpatialReferences.Wgs84));
}
MapService.OnMapClicked -= handler;
};
MapService.OnMapClicked += handler;
return tcs.Task;
}
public void StopSegment(){
// interrupt the CollectPoints task.
_cancellationToken.Cancel();
}
這裏是我的視圖模型的相關部分:
public SegmentRecorder SegmentRecorder { get; }
public RelayCommand StopSegment { get; }
public ViewModel(){
StopSegment = new RelayCommand(ExecuteStopSegment);
SegmentRecorder = new SegmentRecorder();
}
// execute on cancel button click.
public void ExecuteStopSegment(){
SegmentRecorder.StopSegment();
}
當我把一個斷點就行了while (!token.IsCancellationRequested)
,點擊取消按鈕,我從來沒有達到這一點。
我是否在這裏以正確的方式使用取消標記?
旁註:你不應該使用'異步void'因爲這是不是一個事件處理程序的方法。 – dymanoid
您還需要處理'CollectPoint'內的取消,這可能就是它現在正在等待的地方。 – JSteward
一旦用戶停止收集點數,他們需要至少收集一個'CollectPoint'任務來完成暫停執行'while'的任務。在'CollectPoint'之外放置'tcs',並在用戶想要停止收集時完成或取消它,然後您的時間將按預期完成。 – JSteward