Reputation: 46823
Say I have an Async call that I want to invoke, and if the call is already running, don't do anything.
In Normal C# I might write the following (ignoring the thread safety issues for a moment)
private bool aysncHappening = false;
private DoWorkInBgThread()
{
if(asyncHappening)
{
return;
}
asyncHappening = true;
RunMeOnABackgroundThread += ()=>
{
try
{
someWorkHere;
}
finally
{
asyncHappening = false;
}
};
}
How can I achieve the same, Execute if Not already running
, with Rx?
Upvotes: 2
Views: 239
Reputation: 19117
The question, as phrased, doesn't lend itself to a satisfactory answer. Rx is built for situations that have streams of events or data which need to be coordinated. For fire and forget scenarios, it's not as strong. That said, here's an approach
bool inProgress = false;
var obsvr = Observer.Create<Unit>((x) =>
{
if (!inProgress)
{
inProgress = true;
Scheduler.ThreadPool.Schedule(() => {
Thread.Sleep(500);
"InBackground".Dump();
inProgress =false;
});
}
});
obsvr.OnNext(Unit.Default);
obsvr.OnNext(Unit.Default);
obsvr.OnNext(Unit.Default);
"main".Dump();
Thread.Sleep(1000);
obsvr.OnNext(Unit.Default);
Thread.Sleep(3000);
Upvotes: 3