您好我尝试更改标签元素,但文字没有变化。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
sendPOST("http://example");
}
public static void sendPOST(string URL)
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(URL);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property of the request to POST.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),request);
allDone.WaitOne();
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes("");
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
//.....
Form1 test = new Form1();
test.statusLabel.Text = responseString; //dont write anything
Console.WriteLine(responseString); //works well
//.....
}
如何更改?
更新:添加更多代码。如何获取现有的Form1实例以更新Form1 LabelField以在asyn完成后显示某些内容?
答案 0 :(得分:0)
根据问题的评论,我猜你可以这样做:将你想要更改的表单实例作为用户定义的对象state
传递给导致GetResponseCallback
被调用的调用(大多数{ {1}}方法允许您传递用户定义的对象,然后在BeginXYZ
中。然后你可以做这样的事情:
IAsyncResult.State
请注意,由于多线程问题,您可能无法更改Form1 test = asynchronousResult.State as Form1;
test.StatusLabel.Text = responseString;
属性,因此必须使用Text
这样做。 SO上有许多线索可以描述这一点。
我现在没有正常工作的代码示例,但如果我没弄错的话,它应该是这样的:
Control.Invoke