1

I have a long running (usually seconds, but..) Web endpoint.

This endpoint should be triggered by AWS Lambda periodically.

In case I'll wait for response in Lambda (C# implementation) this will be counted as Lambda time and I'll be charged.

There is no chance to change the behavior of the endpoint.

I need to request endpoint with C# and do not wait for the response so the endpoint will be triggered, but Lambda execution will complete

dr11
  • 5,166
  • 11
  • 35
  • 77
  • Can you please explain why standard https://www.bing.com/search?q=c%23+fire+and+forget (like https://stackoverflow.com/questions/12803012/fire-and-forget-with-async-vs-old-async-delegate) does not work for you (since you know that tasks aren't equal threads - https://www.bing.com/search?q=c%23+does+task+create+thread ) – Alexei Levenkov Feb 16 '18 at 15:57

2 Answers2

0

Do an async request, but just don't await it.

Underground
  • 127
  • 5
  • It is really not nice to imply the OP did not search for standard way of doing "fire and forget" (https://stackoverflow.com/questions/12803012/fire-and-forget-with-async-vs-old-async-delegate)... Plus while correct you did not cover any pitfalls of this approach... Really would be much better to vote as duplicate instead of trying to beat quality of existing answers with half a sentence. – Alexei Levenkov Feb 16 '18 at 15:59
  • 1
    I have the app with a short running time. I'm executing it, it should 100% make request, but do not wait for the response, and then close. in case I'll simply implement a Task there is no guarantee it will request before the application will request – dr11 Feb 16 '18 at 16:28
0

Below you can find an example of how this can be implemented.

Was tested with HttpListener. In case you will try to return something from the endpoint, it will fail because the connection is already closed.

const string endpoint = "http://localhost:8081/";

var promise = new TaskCompletionSource<bool>();

var task = Task.Factory.StartNew(() =>
{
    var request = WebRequest.Create(endpoint);
    request.ContentType = "application/json";
    request.Method = "POST";
    request.BeginGetRequestStream(x =>
    {
        var r = (HttpWebRequest) x.AsyncState;
        var stream = r.EndGetRequestStream(x);

        var buffer = Encoding.UTF8.GetBytes("{}");
        stream.Write(buffer, 0, buffer.Length);

        request.BeginGetResponse(y => { }, request);

        promise.SetResult(true);

    }, request);
});

promise.Task.Wait();
dr11
  • 5,166
  • 11
  • 35
  • 77