Cross methods timeout for remote service asynchronous call - c#

My code has two main methods which sends tasks to remote (in another process) services for execution, and acknowledge success or failure.
Each task has few steps so it the method AcknowledgeStepComplete must be called several times with this given task (asynchronously).
public void AcknowledgeStepComplete(CollectionTask task)
{
...
}
public void AcknowledgeStepError(CollectionTask task, Exception exception)
{
...
}
public class CollectionTask : ICoordinationTask
{
public TimeSpan Timeout { get; set; }
}
When sending a task step for execution, i want to know if any call to one of these two methods were received, within a given time frame (i.e. step timeout).
if not - invoke the AcknowledgeStepError myself
(otherwise - do nothing).
How can i check this condition, and invoke only if the given condition is met?
Thanks.

Maybe adding this fucnionality to CollectionTask will do the trick
(the syntax is not perfect but the general idea exists):
public class CollectionTask : ICoordinationTask
{
private Timer _taskInternalTimer;
public TimeSpan Timeout { get; set; }
public event TaskTimedOutEventHandler TaskTimedOut;
public CollectionTask ()
{
_taskInternalTimer = new Timer();
_taskInternalTimer.Elapsed += OnTaskInternalTimerElapsed;
_taskInternalTimer.Start();
}
private void OnTaskInternalTimerElapsed(object sender, ElapsedArgs args)
{
if (_taskInternalTimer.TotalMilisecond >= Timeout)
TaskTimedOut(this, new TaskTimedOutEventArgs());
}
}
And use it that way:
in the scope of the CollectionTask instance creation
var task = new CollectionTask();
task.TaskTimedOut += OnTaskTimedOut
the event handle method
private void OnTaskTimedOut(object sender, TaskTimedOutEventArgs args)
{
AcknowledgeStepError(args.Task, new Exception())
}

I'm not sure I understood the question perfectly, but I'll give it a shot..
From my understanding of the question CollectionTask has some property that defines the expiration time of the task.
Something like this:
public class CollectionTask
{
...
public DateTime TaskTimeout;
}
You can define a delegate which will be called each time you enter AcknowledgeComplete
public void AcknowledgeComplete(CollectionTask task)
{
if (AcknowledgeCompleteStarted != null)
AcknowledgeCompleteStarted(this, new AcknowledgeCompleteStartedEventArgs(task))
....
....
}
That way when you enter the method you just notify to some object that was registered to AcknowledgeCompleteStarted event that this event happened, and in the registered method you will be able to run any logic that you desire, such as checking if the task has reached its time out and if so activate AcknowledgeError with an appropriate exception.
it seems that it can be much simpler just by doing:
public void AcknowledgeComplete(CollectionTask task)
{
if (task.Timeout < DateTime.Now)
AcknowledgeError(task, new Exception());
....
....
}
but i'm pretty sure that was not where you were getting at in your question.
If I didn't hit the target of the question feel free to elaborate with some more code examples..
Guy

Related

How to send a message in event handler in akka.net?

I have an actor that has a custom timer that fires events in non real-time intervals. (This is why I cannot use scheduler)
In event handler I want to send a message to self or another actor. I am receiving an NotSupportedException.
I have a custom time source similliar to the NodaTime FakeClock class.
public class NodaTimeControllableClock
{
public void AddInterval(Duration interval);
public Instant Now { get; protected set; }
public event EventHandler<TimeChangedEventArgs<Duration>> TimeChanged;
}
It is used in timer class to trigger events every specified amount of time.
public class NodaTimer
{
Duration Interval { get; set; }
void Start();
void Stop();
bool IsRunning { get; private set; }
event EventHandler<TimerTickedEventArgs> TimerTicked;
}
Now, I create a timer instance for some of my actors and store it inside them.
protected override void PreStart()
{
base.PreStart();
timer.Interval = Duration.FromSeconds(1);
timer.TimerTicked += Timer_TimerTicked;
timer.Start();
}
private void Timer_TimerTicked(object sender, TimerTickedEventArgs e)
{
Self.Tell(new SomeMessage());
//Here I want to send the message to the parent or
//if it's impossible to do so I could queue some message
//to the Self messagebox.
}
What is the pattern to work with sending messages on events? Is there any?
Probably the source of your issues is Self member call made inside Timer_TimerTicked. Reason for this is that Self just like Context is a computed property, that is available only within currently executing actor's thread. If you call it from the outside (another thread like in the case of timer callbacks), it may be not initialized.
Weak solution is just to store reference to Self in some other field, and use that field to send message instead.
Better solution in your case is to use built-in Akka.NET Scheduler, which offers ability to perform actions or make calls in specified time intervals:
class MyActor : ReceiveActor
{
private readonly ICancelable cancelTimer;
public MyActor()
{
var interval = TimeSpan.FromSeconds(1);
cancelTimer = Context.System.Scheduler
.ScheduleTellRepeatedlyCancelable(interval, interval, Self, new SomeMessage(), ActorRefs.NoSender);
}
protected override void PostStop()
{
cancelTimer.Cancel();
base.PostStop();
}
}

Callback-way to work with Events

I do not understand some things of work with callbacks.
I have some third-party code wich connect,disconnect,subscribe to values from some system.
So, the example is:
class Subscriber:ISubscriber
{
public void OnConnected()
{
}
public void OnDisconnected()
{
}
}
Then, it uses:
var subscriber=new Subscriber();
_someSystemObj.CreateConnection(subscriber); //i do not understand how it works there
And then _someSystemObj calls OnConnected or OnDisconnected.
So, i have two questions:
1.How can _someSystemObj calls OnConnected method (it use Observer pattern or may be it use it other way. Can you describe it? Get some schematic code to understand how it may work.
If i want to do many steps when OnDisconnect happens: should i throw some public event to other classes? I mean than i can not do Disconnection in this OnDisconnect method (i have to do some steps in other part of my code and at old version of this API i just rethrow event OnDisconnect on top of my program and then handle it.)
This old version of code looks like:
_server.OnDisconnect+=OnDisconnectHandler;
void OnDisconnectHandler(..)
{
if(OnReconnect!=null)//some public event
OnReconnect(e);// throw on top of my program and then handle it there
}
At new version of API i try to solve it by add public event and when OnDisconnect happens throw it on top:
class Subscriber:ISubscriber
{
public event EventHandler<EventArgs> OnDisconnectedHappens;
public void OnConnected()
{
}
public void OnDisconnected()
{
if(OnDisconnectedHappens!=null)
OnDisconnectedHappens(this,e);//thow on top
}
}
And in some place:
_subscriber.OnDisconnectHappens+=OnDisconnectHandler; //and do my work
Or, may be it not right way. May be i should do something else?
Please,can you give me a some link, that i can learn about this model of event callbacks?
Or, may be i do it correctly?
How can _someSystemObj call OnConnected method?
Well, you gave it a subscriber when you called CreateConnection(subscriber). It's probably implemented something like this:
private readonly List<ISubscriber> _subscribers = new List<ISubscriber>();
public void CreateConnection(ISubscriber subscriber)
{
_subscribers.Add(subscriber);
}
private void OnConnectedNotifySubscribers()
{
foreach (ISubscriber subscriber in _subscribers)
{
subscriber.OnConnected();
}
}
If I want to do many steps when OnDisconnect happens, should I raise some public event to other classes?
That is a valid option, but it can get difficult to debug when there are too many layers in an event chain. Another option is to increase the capability of your Subscriber class so that it can do everything necessary to handle the subscription events.
class EmpoweredSubscriber : ISubscriber
{
private readonly DisconnectWorker _worker;
private readonly DisconnectHelper _helper;
public EmpoweredSubscriber(DisconnectWorker worker, DisconnectHelper helper)
{
_worker = worker;
_helper = helper;
}
public void OnConnected()
{
}
public void OnDisconnected()
{
_worker.DoWork();
_helper.DoHelp();
// more...
}
}

Using async void to implement dataprovider

I have an interface like this
public interface IServerDataProvider
{
string Val1 { get; }
string Val2 { get; }
event EventHandler<EventArgs> Val1Changed;
event EventHandler<EventArgs> Val2Changed;
}
It gives the user access to two strings retrieved from a server and events that are triggered when these strings change.
Learning about async-await in c#, I can make a fairly simple implementation that periodically checks if these values are changed on a server :
public class ServerDataProviderAsync : IServerDataProvider
{
public event EventHandler<EventArgs> Val1Changed;
public event EventHandler<EventArgs> Val2Changed;
private string _val1Url = "someUrl";
private string _val2Url = "otherUrl";
private const int _delayMs = 1000;
public ServerDataProviderAsync()
{
Start();
}
private async void Start()
{
Val1 = await DownloadString(_val1Url);
Val2 = await DownloadString(_val2Url);
Val1UpdateLoop();
Val2UpdateLoop();
}
private async void Val1UpdateLoop()
{
await Task.Delay(_delayMs);
Val1 = await DownloadString(_val2Url);
Val1UpdateLoop();
}
private async void Val2UpdateLoop()
{
await Task.Delay(_delayMs);
Val2 = await DownloadString(_val1Url);
Val2UpdateLoop();
}
private string _val1;
public string Val1
{
get { return _val1; }
private set
{
if (_val1 != value && value != null)
{
_val1 = value;
OnContentChanged(Val1Changed);
}
}
}
private string _val2;
public string Val2
{
//similar to Val1
}
private async Task<string> DownloadString(string url)
{
using (var wb = new WebClient())
{
try { return await wb.DownloadStringTaskAsync(url); }
catch { /*log error*/}
}
return null;
}
private void OnContentChanged(EventHandler<EventArgs> handler)
{
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
And it can be used something like this from MainWindow :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var dataProvider = new ServerDataProviderAsync();
//hook up to events and display strings in GUI
}
}
Now my question is if this is a good implementaion? Is there a better way?
The first part I'm worried about are the async void methods. I've read they should only be used for event handlers. Are they bad in this case? And if so, why?
The other thing I'm worried about is the recursive way the update loops work. But it seems that since it always awaits tasks that are not already finished, it will not keep adding to the call stack.
You should really use an [iterative] infinite loop to create an infinite loop rather than using infinite recursion.
Using recursion means constantly spending the effort to re-create the exact same state machine from scratch each iteration instead of using the perfectly fine state machine that you already have, and it needlessly obfuscates the code and reduces clarity (to the point that you yourself weren't even sure of the possible negative repercussions; you don't want every single other person who reads the code to have to think through the same problem) for no real gain. Additionally, if you want to be able to propagate exceptions generated in this method to the caller (discussed further below) then using recursion has a number of problems, such as completely messing up the call stack, making actually throwing the exception through all of those levels difficult, and also creating a memory leak in that each "finished" state machine wouldn't be able to be cleaned up.
As for the methods being void, that's not particularly problematic. The reason that one would normally want a Task returned is so that you can tell when the operation finishes. Your operations never finish, they run forever. Getting a task that will never be completed isn't really any more or less useful than not getting a task at all in most circumstances.
The only way it might be relevant is error handling. If your loop generates an error and the method is void it needs to be responsible for handling that error itself, because it is conceptually a top level method. If it returns a Task then it gets the luxury of simply throwing that exception to its caller and leaving that caller responsible for handling that Exception. This would be the only reason to not return void for a method that is supposed to run forever.

Making a generic scheduler of Action<T> with Reactive Extensions

I'm experimenting a lot with Reactive Extensions and right now I'm trying to make a system in which I can queue procedures and execute them in whatever fashion I want while being able to send notifications to subscribers.
I currently have my database access encapsulated within a UserAccess class that exposes the method to add a user. In that method I would like to queue an action that adds a user to the database. So I made a JobProcessor of T class that exposes a method QueueJob(Action) and have my User implement this class. My problem is I can't see how to call the Action from within the OnNext method of the Observable because the action takes a User parameter.
My angle of attack must be wrong and there must be a problem with my grasp of the design. For example I know I should somehow pass my user to the QueueJob procedure but I don't know how to do it in a clean way.
public class UserAccess : JobProcessor<User>
{
public void AddUser(User user)
{
QueueJob(usr =>
{
using (var db = new CenterPlaceModelContainer())
{
db.Users.Add(usr);
}
});
[...]
public abstract class JobProcessor<T>
{
// Either Subject<T> or Subject<Action<T>>
private Subject<Action<T>> JobSubject = new Subject<Action<T>>();
public JobProcessor()
{
JobSubject
/* Insert Rx Operators Here */
.Subscribe(OnJobNext, OnJobError, OnJobComplete);
}
private void OnJobNext(Action<T> action)
{
// ???
}
private void OnJobError(Exception exception)
{
}
private void OnJobComplete()
{
}
public void QueueJob(Action<T> action)
{
JobSubject.OnNext(action);
}
}
Edit 1 :
I tried to change the signature of QueueJob to
QueueJob(T entity, Action<T> action)
Now I can do
QueueJob(user, usr => { ... } );
But it does not seem very intuitive. I haven't seen many frameworks in which you pass both the entity and the action. With that I might as well not need the JobProcessor.
Edit 2 :
I changed my JobProcessor's subject type to Subject, removing the T altogether. Since there was no need to include the User in the procedure since I can refer to it externally. The only problem now is if the User I pass to the QueueJob's action changes between the actual time of the Action execution, the user will have the modified information. Undesirable but I guess I will continue looking for a solution.
My code is now (used Buffer for sample) :
public abstract class JobProcessor
{
public Subject<Action> JobSubject = new Subject<Action>();
public JobProcessor()
{
JobSubject
.Buffer(3)
.Subscribe(OnJobNext, OnJobError, OnJobComplete);
}
private void OnJobNext(IList<Action> actionsList)
{
foreach (var element in actionsList)
{
element();
}
}
private void OnJobError(Exception exception)
{
}
private void OnJobComplete()
{
}
public void QueueJob(Action action)
{
JobSubject.OnNext(action);
}
}
First off, I have to agree with Lee and NSGaga that you probably don't want to do it this way - there are other patterns for a Producer/Consumer queue that are far more aligned with what (I think) you are trying to accomplish here.
That said, since I can never resist a challenge...with some minor tweaks, you can remove your immediate problem of "What do I pass into the action?" by just capturing the user parameter passed in and making it a straight-up Action - Here's your code with some modifications:
public class UserAccess : JobProcessor
{
public void AddUser(User user)
{
QueueJob(() =>
{
using (var db = new CenterPlaceModelContainer())
{
db.Users.Add(user);
}
});
[...]
public abstract class JobProcessor
{
// Subject<Action>
private Subject<Action> JobSubject = new Subject<Action>();
public JobProcessor()
{
JobSubject
/* Insert Rx Operators Here */
.Subscribe(OnJobNext, OnJobError, OnJobComplete);
}
private void OnJobNext(Action action)
{
// Log something saying "Yo, I'm executing an action" here?
action();
}
private void OnJobError(Exception exception)
{
// Log something saying "Yo, something broke" here?
}
private void OnJobComplete()
{
// Log something saying "Yo, we shut down" here?
}
public void QueueJob(Action action)
{
JobSubject.OnNext(action);
}
}
I'm not frankly sure what is your `goal' here - but I think you got it backwards a bit...
Normally subject is exposed via property like
IObservable<Action<T>> NewJob {get{return _subject;}}
...or something. (Subject becomes observable - subject is dual in nature - and why it's specific - and a bit controversial - but good for playing around etc.)
And you just call OnNext from inside the class - like you did.
But you do not normally subscribe to the observable yourself
...you let the outside users do that by 'hooking' into your property - and defining subscribe - which gets them new items as they arrive.
This is simplified of course, there are many cases and many uses but this might help I hope
My initial reaction is that IObservable is normally best suited for creating sequences of immutable data structures, not method-pointers/delegates/actions.
Next I would suggest that if you are trying to 'schedule' actions to be processed in a queue fashion, then the IScheduler implementations in Rx seem like a perfect fit!
Alternatively if you are actually trying to create a ProduceConsumer Queue, then I dont think Rx is actually the best fit for this. i.e. if you are putting a heap of messages into a queue and then having some consumers reading these messages off and processing them, I would look to a different framework.
I finalized my design and found something that I like. Here is the code if anyone else needs it.
public class JobProcessor<T> : IDisposable where T : new()
{
private ISubject<Action<T>> jobsProcessor = new Subject<Action<T>>();
private IDisposable disposer;
private T _jobProvider = new T();
public JobProcessor(Func<ISubject<Action<T>>, IObservable<IEnumerable<Action<T>>>> initializer)
{
Console.WriteLine("Entering JobProcessor Constructor");
disposer = initializer(jobsProcessor)
.Subscribe(OnJobsNext, OnJobsError, OnJobsComplete);
Console.WriteLine("Leaving JobProcessor Constructor");
}
private void OnJobsNext(IEnumerable<Action<T>> actions)
{
Debug.WriteLine("Entering OnJobsNext");
foreach (var action in actions)
{
action(_jobProvider);
}
Debug.WriteLine("Leaving OnJobsNext");
}
private void OnJobsError(Exception ex)
{
Debug.WriteLine("Entering OnJobsError");
Debug.WriteLine(ex.Message);
Debug.WriteLine("Leaving OnJobsError");
}
private void OnJobsComplete()
{
Debug.WriteLine("Entering OnJobsComplete");
Debug.WriteLine("Leaving OnJobsComplete");
}
public void QueueJob(Action<T> action)
{
Debug.WriteLine("Entering QueueJobs");
jobsProcessor.OnNext(action);
Debug.WriteLine("Leaving QueueJobs");
}
public void Dispose()
{
disposer.Dispose();
}
}
I selected a generic make to support an architecture in layers where I could use the JobProcessor in a layer of concurrency where I could select how fast or slow my execution can be. The JobProcessor constructor takes a Func used to declare the Observable sequence somewhere else in the code and generate a processor that executes jobs an the order described by the sequence. The OnNext takes in an IEnumerable> to be able to support sequences like .Buffer(3) that returns a batch of actions at the same time. The downside to that is that when creating a sequence returning single actions at a time I need to do this
var x = new JobProcessor<DatabaseAccess<User>>(subject => subject.Select(action => action.Yield()));
The Yield() extension methof of T returns an enumerable of a single element. I found it here Passing a single item as IEnumerable<T>.

Is there a common pattern for initializing object on a background thread?

I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
I think that a better design would be an asynchronous factory, where the calling code awaits the object creation and then receives a regular object instance.
Stealing liberally from Stephen Toub:
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<T> valueFactory) :
base(() => Task.Run(valueFactory)) { }
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Run(taskFactory)) { }
public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}
public static class ExposeSomeInterestingItemsFactory
{
public static AsyncLazy<ExposeSomeInterestingItems> Instance
{
get { return _instance; }
}
private static readonly AsyncLazy<ExposeSomeInterestingItems> _instance =
new AsyncLazy<ExposeSomeInterestingItems>(() => new ExposeSomeInterestingItems());
public static void StartInitialization()
{
var unused = Instance.Value;
}
}
public class ExposeSomeInterestingItems
{
public ExposeSomeInterestingItems()
{
// This takes some time to load
this._interestingItems = InterestingItemsLoader.LoadItems();
}
public InterestingItem GetItem(string id)
{
// Regular logic. No "delays".
}
}
...
var exposeSomeInterestingItems = await ExposeSomeInterestingItemsFactory.Instance;
var item = exposeSomeInterestingItems.GetItem("id");
That way, you keep the Single Responsibility Principle nicely:
AsyncLazy<T> combines Task<T> with Lazy<T> (so the instance is created asynchronously only when needed).
ExposeSomeInterestingItemsFactory contains construction logic.
ExposeSomeInterestingItems is only concerned with exposing interesting items, rather than having to pollute all its members with asynchronous delays.
Also, this solution is asynchronous throughout (no blocking), which is good (particularly for Metro apps).
Update, 2012-09-14: I've taken this code and cleaned it up and commented it on my blog.
You can use the Task<T> for this. This will take care of all the synchronisation for you and allows you to block untill the value is available:
private static Task<HeavyObject> heavyObjectInitializer;
// Call this method during application initialization
public static void Bootstrap()
{
heavyObjectInitializer = new Task<HeavyObject>(() =>
{
// creation of heavy object here
return new HeavyObject();
});
// Start running the initialization right now on a
// background thread. We don't have to wait on this.
heavyObjectInitializer.Start();
}
// Call this method whenever you need to use the object.
public static HeavyObject GetHeavyObject()
{
// Get the initialized object, or block untill this
// instance gets available.
return heavyObjectInitializer.Result;
}
Optionally, you can also query to see if the object is available or not:
public static bool IsHeavyObjectAvailable
{
get { return heavyObjectInitializer.IsCompleted; }
}
Put the method calls into a queue which you process when you finish initialising. Only put methods into the queue when you have not yet initialised.
You could move to a an event driven architecture where you application is in different states.
Initially the application moves into the Starting state. In this state HeavyObject is created using a background task. When the initialization is complete an event is fired. (You don't have to use an actual .NET event. You can use callbacks or something similar and frameworks like Reactive Extensions allows you to compose sequences of events.)
When all initialization events have fired you move into the Started state of your application. For an UI application this could modify the UI to enable some previously disabled operations.
Check this Prototype Pattern. Maybe it can help you
You only need to create your object once and clone it when you need another one.

Categories