I’m trying to create a async wrapper for my project so that I can tidy up my code and not write the same code over and over again for the objects I’m sending back and forth with the server.
I’m planning to use protobuf, but for the sake of this thread I’ve changed the object to string.
My mambo-jambo code:
public class AsyncWrapper
{
public void Run(Uri url, string requestString, string responseString, WebHeaderCollection headerCollection)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Headers = headerCollection;
request.BeginGetRequestStream((s) =>
{
var req = (HttpWebRequest)s.AsyncState;
var str = req.EndGetRequestStream(s);
System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
Byte[] bytes = encoding.GetBytes(responseString);
str.Write(bytes, 0, bytes.Length);
str.Close();
req.BeginGetResponse((k) =>
{
var req2 = (HttpWebRequest)k.AsyncState;
var resp = (HttpWebResponse)req2.EndGetResponse(k);
byte[] bytes2 = ReadFully(resp.GetResponseStream());
string res = System.Text.Encoding.Unicode.GetString(bytes2);
}, req);
}, null);
}
private static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
What I’m trying to do is create one function that wraps the whole procedure of the “two-step” way of communication with the server: first the initial request, then the response.
Am I on the right path? I’m missing a crucial part; eventhandling. The plan was to rais an event at string res = System... to let the application know that the job is done.
If I’m understanding correctly, you want to turn a long synchronous operation in an asynchronous operation. You can do that with threading: