我正在使用 Visual Web Express 2010。我正在尝试将文件上传到服务器并阻止调用函数并在上传完成后释放它。但是,主线程永远不会被解除阻塞。
public partial class MainPage : UserControl
{
private FileStream fileStream;
private static String responseStr = "";
private static ManualResetEvent evt = new ManualResetEvent(false);
public MainPage()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("App", this);
}
public void sendPhoto()
{
uploadFile();
}
private void uploadFile()
{
uploadDataToServer(url);
evt.WaitOne();
postProcess();
}
public static void postProcess()
{
HtmlPage.Window.Invoke("postProcess2", responseStr);
}
void uploadDataToServer(String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=---------------------------" + _boundaryNo;
request.Method = "POST";
request.BeginGetRequestStream(writeCallback, request);
}
private void writeCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
MemoryStream memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);
if (memoryStream != null)
{
memoryStream.Position = 0;
byte[] img = memoryStream.ToArray();
Stream postStream = request.EndGetRequestStream(asynchronousResult);
postStream.Write(img, 0, img.Length);
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
streamRead.Close();
streamResponse.Close();
response.Close();
responseStr = responseString;
evt.Set();
}
}
现在,当我evt.WaitOne()
在uploadFile 中使用时,整个应用程序都在等待并且没有请求发送到服务器,即代码永远不会到达getResponseCallBack
,因此应用程序永远不会唤醒。但是,如果我不使用evt.WaitOne()
,那么请求是成功的,但是我无法读取响应文本,因为它是在writeCallBack()
函数中设置的并且请求是异步的。我应该怎么做才能克服这个问题?
我想不通: 1.如果请求是多线程/异步的,为什么evt.WaitOne()让整个app等待,请求没有完成? 2. 如果请求是单线程的,那么为什么 postProcess() [删除 evt.WaitOne()] 在尝试访问 responseStr [在 getResponseCallBack() 中设置] 时没有得到正确的响应集。
[对不起,我是新手,很困惑]。
谢谢。
抱歉,我忘了提一件事,我正在使用silverlight
.