I am using RX for the first time, and I have a couple of questions.
1) Is there a better way to run Async in my collection?
2) I need to block the thread until all Async tasks are complete, how to do it?
class Program
{
internal class MyClass
{
private readonly List<int> _myData = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private readonly Random random = new Random();
public int DoSomething(int j)
{
int i = random.Next(j * 1000) - (j * 200);
i = i < 0 ? 1000 : i;
Thread.Sleep(i);
Console.WriteLine(j);
return j;
}
public IObservable<int> DoSomethingAsync(int j)
{
return Observable.CreateWithDisposable<int>(
o => Observable.ToAsync<int, int>(DoSomething)(j).Subscribe(o)
);
}
public void CreateTasks()
{
_myData.ToObservable(Scheduler.NewThread).Subscribe(
onNext: (i) => DoSomethingAsync(i).Subscribe(),
onCompleted: () => Console.WriteLine("Completed")
);
}
}
static void Main(string[] args)
{
MyClass test = new MyClass();
test.CreateTasks();
Console.ReadKey();
}
}
(Note: I know I could use Observable.Range for my Int list, but my list is not of type Int in a real program).
source
share