-1

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!

1 Answers1

0

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.

  • Thanks. If I'm going to throw an exception from the scope of the timer, it will be thrown in a different thread. Same problem IMO. – Usagi Yojimbo 2.0 Dec 07 '17 at 09:45
  • you can take a look in that exception handling in another thread here: https://stackoverflow.com/questions/5983779/catch-exception-that-is-thrown-in-different-thread – Osama Yaser Dec 07 '17 at 10:12