2

Hello I have a wrapservice which calls sub services in the project. I am trying to add timeout value as a second but there is too many variables so it makes thing hard to implement. I am adding my code snippet and open to ideas thank you

public Stream Posnet(Stream request)
    {
        if (!Globals.IsConsumerAuthorizedForWasService)
        {
            throw new FaultException("consumer is not authorized", new FaultCode("3001"));
        }

        var streamReader = new StreamReader(request);
        string streamString = streamReader.ReadToEnd();
        streamReader.Close();

        PosnetResponse resp = _merchantLegacyAPIWrapper.WrapService(streamString); // I want to add timeout here where I call WrapService;
// I want to add timeout here where I call WrapService

        string responseXml = SerializeResponse(resp);
        return GenerateStreamFromString(responseXml);

    }

and I tried this code snippet below to implement but not succeed:

    using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");
  • 2
    Dont use Task.Wait. Use a CancellationToken. You can set a Timeout on it to auto-cancel. – Fildor Jun 14 '22 at 09:29
  • @Fildor I tried but couldnt add it on my code because, it says that return doesnt see the local variable since it is in a code snippet –  Jun 14 '22 at 09:39
  • 1
    Maybe you can use some variation of this: https://dotnetfiddle.net/j3fxHq ? – Fildor Jun 14 '22 at 09:45
  • @Fildor is there way to do this not async? –  Jun 14 '22 at 10:07
  • 1
    What do you mean by "timeout", [there is no good way to non-cooperatively cancel an operation](https://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort/1560567#1560567). I.e. You have to modify `WrapService` so it takes a cancellationToken and regularly checks if it has been cancelled. If you do not have control of the code in `WrapService` you are more or less out of luck, then the best you can do is to run the code in a background thread, and return early, letting the background thread continue on, without anyone caring about the result. – JonasH Jun 14 '22 at 11:45
  • Not-Async would incorporate at least a blocked thread. Which is not really desirable. Or a Timer, perhaps, but then you'd still need to find a way to cancel the operation. – Fildor Jun 14 '22 at 11:56

0 Answers0