You should use Microsoft's Reactive Framework (aka Rx) - NuGet System.Reactive.Windows.Threading
(for WPF) and add using System.Reactive.Linq;
- then you can do this:
public MainWindow()
{
InitializeComponent();
_subscription =
Observable
.FromEventPattern<SizeChangedEventHandler, SizeChangedEventArgs>(
h => container.SizeChanged += h,
h => container.SizeChanged -= h)
.Select(e => GetWidth())
.Select(w => Observable.Start(
() => String.Concat(Enumerable.Range(0, 1000).Select(n => Functionx(w)))))
.Switch()
.ObserveOnDispatcher()
.Subscribe(t => ShowText(t));
}
private IDisposable _subscription = null;
That's all the code needed.
This responds to the SizeChanged
event, calls GetWidth
and then pushes the Functionx
to another thread. It uses Switch()
to always switch to the latest SizeChanged
and then ignores any in-flight code. It pushes the result to the dispatcher and then calls ShowText
.
If you need to close the form or stop the subscription running just call _subscription.Dispose()
.
Simple.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…