我正在尝试为我的项目创建一个异步包装器,以便我可以整理我的代码而不是一遍又一遍地为我正在与服务器来回发送的对象编写相同的代码。
我打算使用protobuf,但为了这个线程,我已经将对象更改为字符串。
我的mambo-jambo代码:
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();
}
}
}
我要做的是创建一个函数来包装与服务器“两步”通信方式的整个过程:首先是初始请求,然后是响应。
我是在正确的道路上吗?我错过了一个关键部分; eventhandling。计划是在string res = System...
举办活动,让应用程序知道工作已经完成。
答案 0 :(得分:1)
如果我理解正确,您希望在异步操作中转换长同步操作。你可以用线程来做到这一点:
public class AsyncWrapper
{
public event Action<string> RunCompleted;
public void Run(Uri url, string requestString, string responseString, WebHeaderCollection headerCollection)
{
Thread thread = new Thread(new ParameterizedThreadStart(RunThread));
thread.start(new [] { url, requestString, responseString, headerCollection });
}
public void RunThread(object Obj)
{
object[] ObjArray = (object[])Obj;
Uri url = (Uri)ObjArray[0];
string requestString = (string)ObjArray[1];
string responseString = (string)ObjArray[2];
WebHeaderCollection headerCollection = (WebHeaderCollection)ObjArray[3];
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);
if (RunComleted != null)
{
RunCompleted(res);
}
}
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();
}
}
}