无法从C#/XAML中的无限循环中取消backgroundWorker

本文关键字:无限循环 取消 backgroundWorker XAML | 更新日期: 2023-09-27 18:11:08

第2版:

在添加了下面的答案之后,我还必须去掉占位符while(true);无限循环。到目前为止,这是有效的,可能也应该有效。

private void lookForXml(object sender, DoWorkEventArgs e)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"''filepath";
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite| 
            NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.xml";
        watcher.Created += new FileSystemEventHandler(OnCreated);
        watcher.EnableRaisingEvents = true;
        BackgroundWorker bw = sender as BackgroundWorker;
        while (!bw.CancellationPending) {
            if (bw.CancellationPending)
            {
                e.Cancel = true;
            }
        }
    }

编辑:

将我的XAML更改为:之后

<Button Content="End" Style="{StaticResource LargeButton}" Command="{Binding EndCommand}"/>

我在EndXmlImport中得到一个NullReferenceError,它表明我的bgWorker没有设置为对象的实例。所以我想我该如何将我的取消按钮与当前正在运行的进程关联起来,以便取消它?


我目前正在尝试编写一个程序,该程序将在目录中查找XML文件,直到用户告诉该程序停止。然而,我似乎无法将我按下的取消按钮与BackgroundWorker的取消联系起来。我不知道如何链接XAML中的取消按钮来取消backgroundWorker进程。

XAML:

<Button Content="Import" Style="{StaticResource LargeButton}" Margin="0 20 0 0" Command="{Binding ImportCommand}"/>
<Button Content="End" Style="{StaticResource LargeButton}"  Command="{Binding EndXmlImport}"/>

C#:

public SubmissionImporterViewModel()
{
    ImportCommand = new RelayCommand(ImportSubmission) ;
    EndCommand = new RelayCommand(EndXmlImport);
}
public void EndXmlImport(object sender)
{
    BackgroundWorker bgWorker = sender as BackgroundWorker;
    bgWorker.CancelAsync();
}
public void ImportSubmission(object o)
{
    BackgroundWorker bgWorker = new BackgroundWorker();
    bgWorker.DoWork += new DoWorkEventHandler(lookForXml);
    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(afterCancel);
    bgWorker.WorkerSupportsCancellation = true;
    Status = "Looking for .xml files";
    bgWorker.RunWorkerAsync();
}

无法从C#/XAML中的无限循环中取消backgroundWorker

您包含在WPF代码中的代码是隐藏的吗?如果是,请将BackgroundWorker设为成员引用,以便在EndXmlImport方法中可以访问它。

public void EndXmlImport(object sender)
{
    bgWorker.CancelAsync();
}
private BackgroundWorker bgWorker;
public void ImportSubmission(object o)
{
    bgWorker = new BackgroundWorker();
    bgWorker.DoWork += new DoWorkEventHandler(lookForXml);
    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(afterCancel);
    bgWorker.WorkerSupportsCancellation = true;
    Status = "Looking for .xml files";
    bgWorker.RunWorkerAsync();
}

是否应该将结束按钮绑定到EndCommand?像这个

<Button Content="End" Style="{StaticResource LargeButton}"  Command="{Binding EndCommand}"/>

如果您使用MVVM设计模式,并将VM绑定到View,那么您可以将bgWorker移动到类级别,然后引用它的EndXmlImport函数,因为您无法在VM上获取sender。

若您使用代码隐藏,那个么发送方不是您的BackgroundWorker,但很可能是按钮实例。