当尝试在单独的类中调用OnProgressChanged和OnCheckCancel时,非静态字段错误需要获取对象引用。这是一个简单的语法错误,但我无法弄清楚。
我使用了以下链接中的代码:BackgroundWorker cancellation
当表单中包含搜索引擎代码时,我可以执行代码,但是我需要这样做,并且我的类库中的许多其他方法都支持背景工作。
//**** Windows Form code (Worker.cs)
public partial class Worker : Form
{
bwSearchEngine bwSE = new bwSearchEngine();
public Worker()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
}
private void btnSearch_Click(object sender, EventArgs e)
{
// set arguments
bw.RunWorkerAsync(arguments);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
bwSE.ProgressChanged += (s, pe) => worker.ReportProgress(pe.ProgressPercentage, pe.UserState);
bwSE.CheckCancel += (sender1, e1) => e1.Cancel = worker.CancellationPending;
e.Result = Search();
}
}
//**** Engine code (bwSearchEngine.cs)
public event ProgressChangedEventHandler ProgressChanged;
public event EventHandler<CancelEventArgs> CheckCancel;
protected virtual void OnProgressChanged(int progress, string message)
{
if (ProgressChanged != null)
{
ProgressChanged(this, new ProgressChangedEventArgs(progress, message));
}
}
protected virtual bool OnCheckCancel()
{
EventHandler<CancelEventArgs> handler = CheckCancel;
if (handler != null)
{
CancelEventArgs e = new CancelEventArgs();
handler(this, e);
return e.Cancel;
}
return false;
}
public class Extensions
{
public static List<HookSet> get_Extensions(string word, SQLiteDataSet hayfield)
{
foreach (DataRow dr ...)
{
// Do processing
if (results.Count > 0 && results.Count % 100 == 0)
{
OnProgressChanged(0, results.Count.ToString()); // ERROR ERROR
if (OnCheckCancel()) // ERROR ERROR
{
break;
}
}
}
}
return (results);
}
答案 0 :(得分:0)
我找到了(某种不受欢迎的解决方案)。类方法get_Extensions是静态方法,因此无法从该方法调用非静态方法OnProgressChanged()。如果将后者设为静态方法,则无法从BackgroundWorker向其中添加事件。因此,似乎我必须使所有与非静态相关的东西,并在使用该类之前创建该类的实例,直到找到更好的解决方案为止。
答案 1 :(得分:0)
我找到了解决方案。我将BackgroundWorker添加为静态方法。我没有在设计模式下将BackgroundWorker添加到表单,而是将其添加到构造函数,并调整了代码以适应静态bw。
private readonly static BackgroundWorker bw = new BackgroundWorker();
public Worker()
{
InitializeComponent();
bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;