调用不起作用? [英] Invoking not working?
问题描述
想知道,如果方法不起作用,那么调用方法有什么意义呢?在过去的7个小时中,我一直努力使其正常运行,但是没有运气.我没有收到错误,只是根本行不通.这是我的代码.
Just wondering, what is the point in invoking a method if it does not work? I have spent the past 7 hours trying to get it to work but had no luck. I dont get an error, it just simply does not work. here is my code.
delegate void StringParameterDelegate(string value);
void UpdateStatus(string value)
{
if (InvokeRequired)
{
// We're not in the UI thread, so we need to call BeginInvoke
BeginInvoke(new StringParameterDelegate(UpdateStatus), new object[] { value });
return;
}
// Must be on the UI thread if we've got this far
rtbChat.Text = value;
}
void OnReceive(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead;
if (handler.Connected)
{
// Read data from the client socket.
try
{
bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Remove(0, state.sb.Length);
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Display Text in Rich Text Box
content = state.sb.ToString();
UpdateStatus(content);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(OnReceive), state);
}
}
catch (SocketException socketException)
{
if (socketException.ErrorCode == 10054 || ((socketException.ErrorCode != 10004) && (socketException.ErrorCode != 10053)))
{
handler.Close();
}
}
}
}
我开始相信这是不可能的.无论我如何设置调用,它都不会更新我的richTextBox,如果我设置为将messageBoz.Show设置为更新状态,则它可以工作,但它永远不会更新richTextBox(rtbChat).
任何帮助将不胜感激.
在此先谢谢您.
I am beginning to believe that it is not possible. No matter how I set up the invoke it simply does not update my richTextBox, if I set put a messageBoz.Show in the update status it works, but it never updates the richTextBox(rtbChat).
Any help would be greatly appriciated.
Thanks in advance.
推荐答案
请尝试以下操作操作您的UpdateStatus函数;
Try the following for your UpdateStatus function;
private void UpdateStatus(string text)
{
if (rtbChat.InvokeRequired)
{
StringParameterDelegate d = new StringParameterDelegate(UpdateStatus);
this.Invoke(d, new object[] { text });
}
else
{
rtbChat.Text = text;
}
}
或者不需要自定义委托:
Or without the need for a custom delegate:
void UpdateText(string value)
{
if (InvokeRequired)
Invoke(new MethodInvoker(delegate { UpdateText(value); }));
else
rtbChat.Text = value;
}
[添加]发表了有关此的提示,已引起一些替代方法和一些有趣的讨论 ^ ].
[Added] Posted a Tip about this which has attracted some alternative methods and some interesting discussion here[^].
这篇关于调用不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!