如果你将它包装在一个帮助器类中,你可以让帮助器“同步”你的值:
public class AsyncWrapper<X,Y>
{
ManualResetEvent mre;
private Y result;
public Y Transform(X x, YourClass yourClass)
{
mre = new ManualResetEvent(false);
result = default(Y);
yourClass.Transform<X,Y>(x, this.OnComplete);
mre.WaitOne();
return result;
}
void OnComplete(Y y)
{
result = y;
mre.Set();
}
}
然后你可以这样使用:
// instance your class with the Transform operation
YourClass yourClass = new YourClass();
AsyncWrapper<X,Y> wrapper = new AsyncWrapper<X,Y>();
foreach(X x in theXCollection)
{
Y result = wrapper.Transform(x, yourClass);
// Do something with result
}
编辑:
既然你说你试图这样做是为了让一切都在后台线程上运行,你可以使用我上面的代码,然后:
// Start "throbber"
Task.Factory.StartNew () =>
{
// instance your class with the Transform operation
YourClass yourClass = new YourClass();
AsyncWrapper<X,Y> wrapper = new AsyncWrapper<X,Y>();
foreach(X x in theXCollection)
{
Y result = wrapper.Transform(x, yourClass);
// Do something with result
}
}).ContinueWith( t =>
{
// Stop Throbber
}, TaskScheduler.FromCurrentSynchronizationContext());
这将在后台线程上启动整个(现在是同步的)进程,并在完成后在 UI 线程上禁用你的“throbber”(来自评论)。
如果你控制了所有这些代码,你可以让你的 Transform 进程从一开始就同步,然后像上面一样将它移动到后台线程中,避免需要包装器。