Created
May 11, 2012 07:27
-
-
Save runceel/2658124 to your computer and use it in GitHub Desktop.
非同期処理を順次実行
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reactive; | |
using System.Reactive.Linq; | |
using System.Reactive.Subjects; | |
using System.ServiceModel.DomainServices.Client; | |
using System.Windows; | |
using System.Windows.Controls; | |
using SilverlightApplication1.Web; | |
namespace SilverlightApplication1 | |
{ | |
public partial class MainPage : UserControl | |
{ | |
public MainPage() | |
{ | |
InitializeComponent(); | |
} | |
private void Button_Click_1(object sender, RoutedEventArgs e) | |
{ | |
var classes = Enumerable.Range(1, 10).Select(_ => new DomainContextHolder()).ToArray(); | |
Observable.Concat( | |
classes | |
.ToObservable() | |
.Select(c => c.AsyncMethod())) | |
.Subscribe(); | |
} | |
} | |
public class DomainContextHolder | |
{ | |
private PeopleDomainContext context = new PeopleDomainContext(); | |
public IObservable<Unit> AsyncMethod() | |
{ | |
var q = context.LoadPeopleQuery(); | |
return context.LoadAsObservable(q) | |
// 外部に結果を返したくないならUnitにしとく | |
.Select(_ => Unit.Default); | |
} | |
} | |
public static class DomainContextExtensions | |
{ | |
public static IObservable<IEnumerable<TEntity>> LoadAsObservable<TEntity>(this DomainContext self, EntityQuery<TEntity> query) | |
where TEntity : Entity | |
{ | |
return Observable.Defer(() => | |
{ | |
var async = new AsyncSubject<IEnumerable<TEntity>>(); | |
var op = self.Load(query); | |
Observable.FromEvent<EventHandler, EventArgs>( | |
h => (s, e) => h(e), | |
h => op.Completed += h, | |
h => op.Completed -= h) | |
.Take(1) | |
.Subscribe(_ => | |
{ | |
if (op.IsCanceled) | |
{ | |
async.OnCompleted(); | |
return; | |
} | |
if (op.HasError) | |
{ | |
op.MarkErrorAsHandled(); | |
async.OnError(op.Error); | |
return; | |
} | |
async.OnNext(op.Entities); | |
async.OnCompleted(); | |
}); | |
return async.AsObservable(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment