C# 在c中使用后台工作程序#
我一直在尝试使用c#中的后台工作人员来帮助我使用MSMQ程序 当程序加载时,它会创建一个名为bgwMSMQ的新后台工作程序 到目前为止,我掌握的代码是:C# 在c中使用后台工作程序#,c#,backgroundworker,msmq,C#,Backgroundworker,Msmq,我一直在尝试使用c#中的后台工作人员来帮助我使用MSMQ程序 当程序加载时,它会创建一个名为bgwMSMQ的新后台工作程序 到目前为止,我掌握的代码是: private void btnSendMsg_Click(object sender, EventArgs e) { if (bgwMSMQ.IsBusy != true) { btnAbort.Enabled = true; btnSendMsg
private void btnSendMsg_Click(object sender, EventArgs e)
{
if (bgwMSMQ.IsBusy != true)
{
btnAbort.Enabled = true;
btnSendMsg.Enabled = false;
bgwMSMQ.RunWorkerAsync();
}
}
private void btnAbort_Click(object sender, EventArgs e)
{
if (bgwMSMQ.WorkerSupportsCancellation == true)
{
btnAbort.Enabled = false;
btnSendMsg.Enabled = true;
bgwMSMQ.CancelAsync();
}
}
这些是我的纽扣
private void bgwMSMQ_DoWork(object sender, DoWorkEventArgs e)
{
/*txtPrevTiming.Invoke((MethodInvoker)delegate
{
txtPrevTiming.Text = txtTiming.Text;
});*/
txtPrevTiming.Text = txtTiming.Text;
ClearResponse();
SendMessage(prepareMsg(txtMsgSent.Text), true, true);
}
是工作代码。该程序的目的是创建一个后台进程,用于发送和接收MSMQ消息。到目前为止,它的工作原理是,我可以发送一条消息,如果它完成了发送、接收循环,就没有问题了
但是,我需要使它,如果没有消息返回时,我按下中止按钮,它将停止监听响应消息,而不是等待超时
当我点击abort时,它不会取消操作,它会发送一个取消操作的请求,而我仍然停留在循环中,等待响应消息超时
你知道怎么做才能让“中止”按钮取消监听响应消息的操作并停止后台工作程序吗
谢谢
try
{
int iObjId = (ObjectId.Length == 0) ? 0 : Convert.ToInt32(ObjectId);
msgSend.Label = createLabel();
//
msgSend.BodyType = (int)VarEnum.VT_BSTR;
msgSend.Body = SentMsg;
//
//sentMsg.BodyStream = new MemoryStream(Encoding.UTF8.GetBytes(SentMsg));
mqRequest.Send(msgSend);
Stopwatch.Restart();
String strMsgId = msgSend.Id;
CorrelationId = msgSend.Id;
if (!bGetResponse)
{
return true;
}
if (!getAnswer(ref mqResponse, CorrelationId, true))
{
if (!getError(ref mqError, CorrelationId, true))
{
showError("Could not retrieve Response or Error");
return false;
}
}
}
catch (System.Exception ex)
{
//showError.Invoke((Action<string>)delegate
//{
showError(String.Format("Error \"{0}\" occurred when trying to send a message", ex.Message));
//});
return false;
}
试试看
{
intiobjid=(ObjectId.Length==0)?0:Convert.ToInt32(ObjectId);
msgSend.Label=createLabel();
//
msgSend.BodyType=(int)VarEnum.vtbstr;
msgSend.Body=SentMsg;
//
//sentMsg.BodyStream=newmemoryStream(Encoding.UTF8.GetBytes(sentMsg));
mqRequest.Send(msgSend);
Stopwatch.Restart();
字符串strMsgId=msgSend.Id;
CorrelationId=msgSend.Id;
如果(!bGetResponse)
{
返回true;
}
if(!getAnswer(ref mqResponse,CorrelationId,true))
{
if(!getError(ref mqError,CorrelationId,true))
{
淋浴错误(“无法检索响应或错误”);
返回false;
}
}
}
catch(System.Exception-ex)
{
//调用((操作)委托
//{
淋浴错误(String.Format(“尝试发送消息时发生错误\“{0}\”,例如message));
//});
返回false;
}
是send函数,发送一条消息并调用GetAnsewr,该函数调用ReceiveByCorrelationId为什么要注释掉调用部分?代码在哪里等待响应?对于
BackgroundWorker
,这看起来不是正确的作业。顺便说一句,您可以使用任务或线程池来异步执行短任务。IMHO,BackgroundWorker-选择错误,除非这是你在c语言上的第一周,否则我通常不会用c语言编写代码,因为我在这方面从来没有任何经验,这实际上是我第一次使用它。调用代码在我测试时被注释掉了。现在,响应代码被隐藏在SendMessage函数中。Send message函数发送消息,然后尝试获取具有相关ID的消息。我尝试使用Task和async命令,但它不断给我一个错误,说我没有大声传递任务中的引用,我传递了队列对象