Home Timeout in Async Method

# Timeout in Async Method

Usagi Yojimbo
1#
Usagi Yojimbo Published in 2017-12-07 09:29:33Z
 I have an async Method named "RequestMessage()". Within this method, I'm going to send a message to a message broker. Since I don't know when to expect the result, I'm using "TaskCompletionSource". I want the async method to terminate, when the reply message arrived (I'll receive an event from the broker). This works fine so far. Now, my issue is that this message could never be answered, or at least way to late. I'm looking for a change to implement my own timeout. To do so, I tried a Timer, as well as the Observer of Reactive Extensions. Th issue is always the same - I can't get my main thread and the timer thread syncronized, as I'm using .NET Core 2 and there is no SynchronizationContext. So, in my code there is an observer ..  Observable .Interval(TimeSpan.FromSeconds(timeOutInSeconds)) .Subscribe( x => { timeoutCallback(); });  If time expires a callback should be called. In my caller method, I handle the callback this way:  TimeoutDelegate timeoutHandler = () => throw new WorkcenterRepositoryCommunicationException("Broker communication timed out.", null);  As you realized already, this Exception will never be catched, as it is not thrown to the main thread. How can I sync threads here? Thanks in advance!
Osama Yaser
2#
Osama Yaser Reply to 2017-12-07 09:39:40Z
 The best way to "fail upon some problem" IMHO would be to throw the appropriate exception, but you can definitely just use return; if you prefer to avoid exceptions. This will create a completed/faulted task that was completed synchronously, so the caller using await will get a finished task and continue on using the same thread. CancellationToken allows for the caller to cancel the operation, which isn't the case you are describing. Task.Yield doesn't terminate any operation, it just enables other tasks to run for some time and reschedules itself for later.
 You need to login account before you can post.
Processed in 0.324308 second(s) , Gzip On .