I am using the Gadgeteer FEZ Spider, ENC28 Ethernet module, button module, MF 4.2.
When httpWebRequest.getresponse() is called and the function does not return for many seconds waiting for the web server’s response, pressing the button does not cause the event handler to be called and the LED does not turn on, with Button.LEDModes.OnWhilePressed. I have spawned a thread to call getresponse() but that does not help. I tried calling thread.join(100) and thread.sleep(0) while waiting for the thread to finish, but that does not help. There is no asynchronous version of getresponse() in NETMF. How can I call getresponse() and keep the devices responsive while waiting for a response?
Here is my code:
private HttpWebRequest reqParam=null;
private HttpWebResponse respParam=null;
private HttpWebResponse GetResponseAsync(HttpWebRequest req)
{
try
{
respParam = null;
reqParam = req;
ThreadStart starter = new ThreadStart(getResponseFunction);
Thread th = new Thread(starter);
th.Start();
counter = AsyncTimeout/100;
while (!th.Join(100))
{
Thread.Sleep(0);
--counter;
if (counter <= 0)
{
th.Abort();
throw new System.Net.WebException("HTTP connection timeout");//InvalidOperationException("Timeout!");
}
}
}
finally
{
}
return respParam;
}
private void getResponseFunction()
{
try
{
respParam = (HttpWebResponse)reqParam.GetResponse();
}
catch (Exception) { }
}
private WebResponse MakeRequest(string url, object obj, string Method, string id, string key)
{
Debug.Print("Request: " + url);
using (HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest)
{
req.Method = Method;
req.ContentType = ContentType;
req.KeepAlive = false;
req.Headers.Add(IdHeader, id);
req.Headers.Add(KeyHeader, key);
req.ReadWriteTimeout = AsyncTimeout;
req.Timeout = AsyncTimeout;
if (obj != null)
{
JsonFormatter js = new JsonFormatter();
string s = js.ToJson(obj);
req.ContentLength = s.Length;
using (Stream rs = req.GetRequestStream())
{
rs.Write(Encoding.UTF8.GetBytes(s), 0, s.Length);
rs.Close();
}
}
HttpWebResponse resp = GetResponseAsync(req); //(HttpWebResponse)req.GetResponse(); //
Debug.Print("Done. Response code = " + resp.StatusCode.ToString());
return resp;
}
}