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

时间:2014-07-02 19:57:15

标签: c# wpf xaml backgroundworker

EDIT2:

在添加下面的答案后,我还必须摆脱占位符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中的取消按钮以取消后台工作进程。

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();
}

2 个答案:

答案 0 :(得分:0)

你不能将结束按钮绑定到EndCommand吗?喜欢这个

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

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

如果您使用后面的代码,那么发件人不是您的BackgroundWorker,但很可能是它的按钮实例。

答案 1 :(得分:0)

您在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();
}