Adding a timeout in a specific part of code in c# programming language

Viewed 60

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");
0 Answers
Related