【发布时间】:2015-01-24 03:59:18
【问题描述】:
我在尝试取消 Backgroundworker 时遇到了一些麻烦。 我已经阅读了几十个类似的主题,例如How to stop BackgroundWorker correctly、How to wait correctly until BackgroundWorker completes?,但我没有到达任何地方。
发生的事情是我有一个 C# 应用程序,它使用 PHP WebService 将信息发送到 MySQL 数据库。如果用户出于某种原因(在表单中)单击“返回”或“停止”按钮,则会触发以下代码:
BgWorkDocuments.CancelAsync();
BgWorkArticles.CancelAsync();
我知道请求是Asynchronous,因此取消可能需要 1 或 2 秒,但它应该会停止......而且这根本不会发生。即使点击“返回”(当前表单已关闭并打开一个新表单),后台工作程序仍继续工作,因为我不断看到数据被插入 MySQL。
foreach (string[] conn in lines)
{
string connectionString = conn[0];
FbConnection fbConn = new FbConnection(connectionString);
fbConn.Open();
getDocuments(fbConn);
// Checks if one of the backgrounds is currently busy
// If it is, then keep pushing the events until stop.
// Only after everything is completed is when it's allowed to close the connection.
//
// OBS: Might the problem be here?
while (BgWorkDocuments.IsBusy == true || BgWorkArticles.IsBusy == true)
{
Application.DoEvents();
}
fbConn.Close();
}
需要上面的代码,因为我可能有多个数据库,这就是我有循环的原因。
private void getDocuments(FbConnection fbConn)
{
BgWorkDocuments.RunWorkerAsync();
BgWorkDocuments.DoWork += (object _sender, DoWorkEventArgs args) =>
{
DataTable dt = getNewDocuments(fbConn);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
// Checks if the user has stopped the background worker
if (BgWorkDocuments.CancellationPending == false)
{
// Continue doing what has to do..
sendDocumentsToMySQL((int)dt.Rows[i]["ID"]);
}
}
// After the previous loop is completed,
// start the new backgroundworker
getArticles(fbConn);
};
}
private void getArticles(FbConnection fbConn)
{
BgWorkArticles.RunWorkerAsync();
BgWorkArticles.DoWork += (object _sender, DoWorkEventArgs args) =>
{
DataTable dt = getNewArticles(fbConn);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
// Checks if the user has stopped the background worker
if (BgWorkArticles.CancellationPending == false)
{
// Continue doing what has to do..
sendArticlesToMySQL((int)dt.Rows[i]["ID"]);
}
}
};
}
【问题讨论】:
-
无论第一个线程发生什么,您都会进入第二个线程。所以在
getDocuments()期间取消不会阻止getArticles()触发。在getDocument()通话中需要return吗? -
然后失去
DoEvents()电话......这是个坏主意。如果您正在寻找另一种刷新方式。 -
我同意你的观点,我已经将验证是否取消的代码更改为:pastebin.com/3uEfNZqa,同样的代码(仅更改后台工作人员名称)也应用于 getArticles() ..但问题仍然存在。
-
查看此模式。 msdn.microsoft.com/en-us/library/…需要传递发件人,取消发件人
-
你在 dowork 事件被附加之前就开始工作了,这是怎么回事?
标签: c# .net backgroundworker