1
\$\begingroup\$

The following code seems to have several redundant Flush, Close and Abort statements despite using the use statement.

This code requests a token using API keys and caches it for efficiency reasons and subsequent usage to avoid requesting token each time until it expires.

You'll notice expiry check (plus some extra 1 sec buffer) token.expires_at.Add (TimeSpan 1000L) followed by either HTTP call or it simply returns the token from the cache.

  1. I have the use requestStream statement along with requestStream.Close(). Is it necessary to close if you are using the use statement? Same with the use reader statement.

  2. request.Abort() do we need to abort the request, I was expecting close or something?

  3. I believe making it asynchronous will make it more efficient. Any help in that regard will be highly appreciated.

Otherwise the code works fine and I need a second pair of eyes to look at it. Please help to reduce the lines of code as much as possible.

let requestToken (): Token =


    if token.expires_at.Add (TimeSpan 1000L) < DateTime.Now then

        let data : byte[] = System.Text.Encoding.ASCII.GetBytes("");

        let url = "https://example.com"

        let request = WebRequest.Create(url) :?> HttpWebRequest
        request.Method <- "POST"
        request.ContentType <- "application/x-www-form-urlencoded"
        request.Accept <- "application/json;charset=UTF-8"
        request.ContentLength <- (int64)data.Length

        use requestStream = request.GetRequestStream() 
        requestStream.Write(data, 0, data.Length)
        requestStream.Flush()
        requestStream.Close()

        let response = request.GetResponse() :?> HttpWebResponse
        use reader = new StreamReader(response.GetResponseStream())

        let result = JsonConvert.DeserializeObject<Token>(reader.ReadToEnd())   

        token.access_token <- result.access_token
        token.token_type <- result.token_type 
        token.expires_in <- result.expires_in
        token.expires_at <- DateTime.Now + TimeSpan.FromMilliseconds(double(result.expires_in))

        reader.Close()
        response.Close()
        request.Abort()

        token
    else 
        token

Usage

let token : Token = requestToken()
\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.