我正在创建一个可观察量,我正在单独创建订阅:
class CustomQuery {
string Name;
IObservable<int> Occurrences;
}
public IEnumerable<CustomQuery> GatherCustomQueryObservables()
{
yield return new CustomQuery() {
Name = "NameXXX",
Occurrences = Observable.Create<int>(
observer =>
{
int occurrences = this.webservice.GetOccurrences()
observer.OnNext(occurrences);
return System.Reactive.Disposables.Disposable.Empty;
}
);
}
另一方面,还有另一种方法可以处理这些CustomQueries
:
public void CommitCustomQueryObservables(IEnumerable<CustomQuery> queries)
{
foreach (CustomQuery query in queries)
{
query.Occurrences
.Select(o => o)
.SubscribeOn(System.Reactive.Concurrency.TaskPoolScheduler.Default)
.ObserveOn(System.Reactive.Concurrency.DispatcherScheduler.Current)
.Subscribe(
occurrences =>
{
string strOccurrences = occurrences > 0 ? occurrences.ToString() : "";
this.Label.Text = strOccurrences;
}
);
}
}
尽管如此,我还是得到了一个System.InvalidOperationException
例外:
当前线程没有与之关联的调度程序。
堆栈跟踪的最后一行位于
System.Reactive.Concurrency.DispatcherScheduler.get_Current().
我不太清楚如何处理它。
有什么想法吗?
对于 Windows 窗体,您需要使用 ControlScheduler 进行同步,而不是 DispatcherScheduler。
现在您已经添加了System.Reactive.Windows.Forms
包,这可以通过简单地使用 [observable].ObserveOn([control])
来实现;在您的示例中,这可能是:
public void CommitCustomQueryObservables(IEnumerable<CustomQuery> queries)
{
foreach (CustomQuery query in queries)
{
query.Occurrences
.Select(o => o)
.SubscribeOn(System.Reactive.Concurrency.TaskPoolScheduler.Default)
.ObserveOn(this.Label)
.Subscribe(
occurrences =>
{
string strOccurrences = occurrences > 0 ? occurrences.ToString() : "";
this.Label.Text = strOccurrences;
}
);
}
}