我正在使用XMPP聊天协议在C#中编程,并希望在GUI中等待计数器部分的响应。它需要不到1秒,直到计数器部分响应(它是一个脚本),所以如果GUI挂起那段时间,这不是问题。我尝试使用ManualResetEvent,但我只是得到一个超时异常。我制作了以下代码(摘录中):
using agsXMPP;
using agsXMPP.protocol.client;
using agsXMPP.Collections;
using agsXMPP.protocol.iq.roster;
using System.Threading;
public partial class Form1 : Form
{
static string output_msg;
private ManualResetEvent manualResetEvent;
public Form1()
{
manualResetEvent = new ManualResetEvent(false);
Jid jidSender = new Jid(username + "@" + server);
xmpp = new XmppClientConnection(jidSender.Server);
xmpp.UseStartTLS = true;
xmpp.Open(jidSender.User, password, resource);
xmpp.OnLogin += new ObjectHandler(OnLogin);
// create message receive callback
xmpp.MessageGrabber.Add(new Jid(JID_Receiver), new BareJidComparer(), new MessageCB(MessageCallBack), null);
// send a message
xmpp.Send(new agsXMPP.protocol.client.Message(new Jid(sendTo), MessageType.chat, message));
// wait with ManualResetEvent, till response is available in output_msg
if (!manualResetEvent.WaitOne(3000))
{
throw new TimeoutException();
}
manualResetEvent.Reset();
// show response in a dataGridView . . .
output.AppendText(output_msg); // output is a TextBox, just for debugging
}
private void MessageCallBack(object sender, agsXMPP.protocol.client.Message msg, object data)
{
output_msg = msg.Body;
manualResetEvent.Set();
}
}
我该如何等待回应?是否有ManualResetEvent的替代方法?