如何使用MVVM / ICommand模式在WPF中正确实现BackgroundWorker

时间:2017-08-03 19:22:08

标签: c# wpf mvvm backgroundworker icommand

我有一个小型WPF应用程序,主要是按照MVVM模式编写的。程序的要点是读取文本文件的行,从中解析数据,将数据写入对象列表,然后将这些对象中的数据写入特定格式的.CSV文件。

尽管我已经按照与其他应用程序一样的方式实现了BackgroundWorker类,但这次我从ICommand的Execute()方法中调用RunWorkAsync()方法。虽然最终输出是正确的,并且应用程序实际上提供了所需的结果,但是在BackgroundWorker运行时,UI STILL会锁定。

我已经将一个名为“ReaderWriter”的类中的BackgroundWorker成员和所有逻辑包含在一个构造函数中,该构造函数将我的ViewModel作为参数。

通过调用我的ReaderWriter实例的“StartProcess”方法,调用BackgroundWorker的RunWorkerAsync() - 这是我希望它将接管另一个线程并执行我长时间运行的读取源文件的过程,解析数据,写入新文件;所有这些都在定期执行ReportProgress()以更新ProgressBar。

以下是我的ReaderWriter类的代码:

class ReaderWriter
{
    private LogDataViewModel vm { get; set; }
    private BackgroundWorker bw { get; set; }

    public ReaderWriter(LogDataViewModel viewModel)
    {
        vm = viewModel;
    }

    public void StartProcess()
    {
        bw = new BackgroundWorker();

        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;
        bw.DoWork += new DoWorkEventHandler(ReadFromSource);
        bw.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress_Read);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed_Read);

        bw.RunWorkerAsync();
    }

    private void ReadFromSource(object sender, DoWorkEventArgs e)
    {
        double records = 0;
        string[] lines = File.ReadAllLines(vm.SourcePath);
        int lineCount = lines.Length;
        double currentLine = 0;

        bw.ReportProgress(0, lineCount);

        foreach (var line in lines)
        {
            if (line.Length > 0)
            {
                string syntax = line.Substring(17, 6);

                switch (syntax)
                {
                    case "$WIMDA":
                        string[] segments = line.Replace(": <- ", ",").Split(',');
                        vm.LineItems.Add(new LineItem()
                        {
                            Time = segments[0],
                            HgPressure = segments[2],
                            BarPressure = segments[4],
                            AirTemp = segments[6],
                            RelHumidity = segments[10],
                            TrueWindDir = segments[14],
                            KnotsWindSpeed = segments[18],
                            MpsWindSpeed = segments[20]
                        });
                        break;

                    case "$GPGGA":
                        break;

                    default:
                        break;
                }
            }
            currentLine++;
            bw.ReportProgress(1, currentLine);
        }
        using (StreamWriter writer = new StreamWriter(vm.OutputPath))
        {
            writer.WriteLine($"Time,Pressure(Bar),Pressure(Hg),AirTemp({((vm.ConvertTempSetting) ? "F" : "C")}),RelativeHumidity,TrueWindDirection,WindSpeed(Knots),WindSpeed(M/s)");
            foreach (var lineItem in vm.LineItems)
            {
                writer.WriteLine($"{lineItem.Time},{lineItem.BarPressure},{lineItem.HgPressure},{((vm.ConvertTempSetting) ? Converters.ConvertFromCelcius(Convert.ToDouble(lineItem.AirTemp)).ToString() : lineItem.AirTemp)},{lineItem.RelHumidity},{lineItem.TrueWindDir},{lineItem.KnotsWindSpeed},{lineItem.MpsWindSpeed}");
                records++;
            }
        }
        e.Result = records;
    }

    private void UpdateProgress_Read(object sender, ProgressChangedEventArgs e)
    {
        vm.IncrementProgress();
        switch (Type.GetTypeCode(e.UserState.GetType()))
        {
            case TypeCode.Double:
                vm.IncrementProgress();
                break;

            case TypeCode.String:
                break;

            case TypeCode.Int32:
                vm.AppendStatus(DateTime.Now, $"{(int)e.UserState} lines parsed from log file");
                break;

            default:
                break;
        }
        if (vm.IsFirst)
        {
            vm.ProgressIsVisible = true;
            vm.IncrementProgress();
            vm.SetMaximum((int)e.UserState);
            vm.IsFirst = false;
        }
    }
    private void Completed_Read(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
        {
            vm.AppendStatus(DateTime.Now, $"Conversion was cancelled by user");
        }
        else
        {
            vm.AppendStatus(DateTime.Now, $"{(double)e.Result} records written to {vm.OutputPath}");
        }
        vm.LineItems.Clear();
    }
}

对于我的ViewModel:

public class LogDataViewModel : LogDataModel
{
    #region Commands
    public BeginProcessCommand BeginCommand { get; set; }
    public SelectOutputPathCommand OutputCommand { get; set; }
    public SelectSourceCommand SourceCommand { get; set; }
    public ResetCommand ResetCommand { get; set; }
    #endregion

    public bool IsFirst { get; set; }

    public LogDataViewModel()
    {
        BeginCommand = new BeginProcessCommand(this);
        OutputCommand = new SelectOutputPathCommand(this);
        SourceCommand = new SelectSourceCommand(this);
        ResetCommand = new ResetCommand(this);

        PrepareViewModel();
    }


    private void PrepareViewModel()
    {
        ProgressValue = 0;
        ProgressMaximum = 0;
        ProgressIsVisible = false;
        IsFirst = true;

        OutputPath = Properties.Settings.Default.RememberedSavePath;
        if (LineItems == null) LineItems = new List<LineItem>();
        if (StatusActions == null) StatusActions = new ObservableCollection<StatusAction>();
        AppendStatus(DateTime.Now, "Initialized Program");
    }
}

最后,这是命令:

public class BeginProcessCommand : ICommand
{
    LogDataViewModel vm;

    public BeginProcessCommand(LogDataViewModel viewModel)
    {
        vm = viewModel;
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        bool result = true;

        if (!File.Exists(vm.SourcePath))
            result = false;
        try
        {
            if (!Directory.Exists(Path.GetDirectoryName(vm.SourcePath)))
                result = false;
        }
        catch
        {
            result = false;
        }
        return result;
    }

    public void Execute(object parameter)
    {
        ReaderWriter rw = new ReaderWriter(vm);
        rw.StartProcess();
    }
}

在这一点上的任何帮助都非常感谢,因为我现在已经努力了一段时间,任何研究解决方案的尝试都无法帮助我的特殊情况。这似乎是一个相当独特的场景,但我希望我们能够使它发挥作用。

谢谢!

1 个答案:

答案 0 :(得分:2)

您正在使用ReportProgress并且经常使用(在文件的每一行上)。它将受到重创,每次调用都会在您的UI中引起某种更新,从而锁定它。

通过传递一个百分比,

ReportProgress可能最容易使用。我不确定你在UpdateProgress_Read中用开关做了什么。最好只在你传递总线数的第100个时进行更新。

将progressBar最大值设置为100

ProgressMaximum = 100;

计算总行数的1%

var x = lineCount / 100;
var y = 0;

并且仅在您传递每个1%时报告进度

currentLine++;
if((currentLine % x) == 0)
{
    y++;
    bw.ReportProgress(y);
}

并更改UpdateProgress_Read,使其仅增加

private void UpdateProgress_Read(object sender, ProgressChangedEventArgs e)
{
    vm.IncrementProgress();
}

你需要提出更好的变量名,然后是x和y!并且如果文件中的行少于100行,还要确定该怎么做。