The following code seems to have several redundant
Abort statements despite using the
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.
I have the
use requestStreamstatement along with
requestStream.Close(). Is it necessary to close if you are using the
usestatement? Same with the
request.Abort()do we need to abort the request, I was expecting close or something?
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
let token : Token = requestToken()