我有许多类可以做一些事情,通常是遍历一个记录集并为每个记录调用一个或两个Web服务。

目前,这一切都在GUI线程中运行并挂画。首先想到的是使用BackgroundWorker并实现一个不错的进度栏,处理错误,完成等。Backgroundworker可以实现所有这些不错的功能。

一旦代码打到屏幕上,它就会开始闻起来。我在每个类中编写了很多后台工作程序,在bw_DoWork方法中重复了大多数ProcessRows方法,并认为应该有更好的方法,而且可能已经完成了。

在我继续工作之前,是否有一种模式或实现可以将背景工作人员与其他人分开?需要使用实现接口(interface)(例如ibackgroundable)的类,但是这些类仍可以独立运行,并且只需很少的更改即可实现该接口(interface)。

编辑:@Henk请求的简化示例:

我有:

    private void buttonUnlockCalls_Click(object sender, EventArgs e)
    {
        UnlockCalls unlockCalls = new UnlockCalls();
        unlockCalls.MaxRowsToProcess = 1000;
        int processedRows = unlockCalls.ProcessRows();
        this.textProcessedRows.text = processedRows.ToString();
    }

我想我想要:
    private void buttonUnlockCalls_Click(object sender, EventArgs e)
    {
        UnlockCalls unlockCalls = new UnlockCalls();
        unlockCalls.MaxRowsToProcess = 1000;

        PushToBackground pushToBackground = new PushToBackground(unlockCalls)
        pushToBackground.GetReturnValue = pushToBackground_GetReturnValue;
        pushToBackground.DoWork();
    }

    private void pushToBackground_GetReturnValue(object sender, EventArgs e)
    {
        int processedRows = e.processedRows;
        this.textProcessedRows.text = processedRows.ToString();
    }

我可以继续执行此操作,但是不想重新发明。

我正在寻找的答案将与“是的,乔(在这里)很好地实现了”或“这是代理窗口小部件模式,请在这里阅读有关内容”类似。

最佳答案

每个操作都需要实现以下接口(interface):

/// <summary>
/// Allows progress to be monitored on a multi step operation
/// </summary>
interface ISteppedOperation
{
    /// <summary>
    /// Move to the next item to be processed.
    /// </summary>
    /// <returns>False if no more items</returns>
    bool MoveNext();

    /// <summary>
    /// Processes the current item
    /// </summary>
    void ProcessCurrent();

    int StepCount { get; }
    int CurrentStep { get; }
}

这将步骤的枚举与处理分开。

这是一个示例操作:
class SampleOperation : ISteppedOperation
{
    private int maxSteps = 100;

    //// The basic way of doing work that I want to monitor
    //public void DoSteppedWork()
    //{
    //    for (int currentStep = 0; currentStep < maxSteps; currentStep++)
    //    {
    //        System.Threading.Thread.Sleep(100);
    //    }
    //}

    // The same thing broken down to implement ISteppedOperation
    private int currentStep = 0; // before the first step
    public bool MoveNext()
    {
        if (currentStep == maxSteps)
            return false;
        else
        {
            currentStep++;
            return true;
        }
    }

    public void ProcessCurrent()
    {
        System.Threading.Thread.Sleep(100);
    }

    public int StepCount
    {
        get { return maxSteps; }
    }

    public int CurrentStep
    {
        get { return currentStep; }
    }

    // Re-implement the original method so it can still be run synchronously
    public void DoSteppedWork()
    {
        while (MoveNext())
            ProcessCurrent();
    }
}

可以从如下形式调用:
private void BackgroundWorkerButton_Click(object sender, EventArgs eventArgs)
{
    var operation = new SampleOperation();

    BackgroundWorkerButton.Enabled = false;

    BackgroundOperation(operation, (s, e) =>
        {
            BackgroundWorkerButton.Enabled = true;
        });
}

private void BackgroundOperation(ISteppedOperation operation, RunWorkerCompletedEventHandler runWorkerCompleted)
{
    var backgroundWorker = new BackgroundWorker();

    backgroundWorker.RunWorkerCompleted += runWorkerCompleted;
    backgroundWorker.WorkerSupportsCancellation = true;
    backgroundWorker.WorkerReportsProgress = true;

    backgroundWorker.DoWork += new DoWorkEventHandler((s, e) =>
    {
        while (operation.MoveNext())
        {
            operation.ProcessCurrent();

            int percentProgress = (100 * operation.CurrentStep) / operation.StepCount;
            backgroundWorker.ReportProgress(percentProgress);

            if (backgroundWorker.CancellationPending) break;
        }
    });

    backgroundWorker.ProgressChanged += new ProgressChangedEventHandler((s, e) =>
    {
        var progressChangedEventArgs = e as ProgressChangedEventArgs;
        this.progressBar1.Value = progressChangedEventArgs.ProgressPercentage;
    });

    backgroundWorker.RunWorkerAsync();
}

我还没有做,但是我将把BackgroundOperation()移到它自己的类中,并实现取消操作的方法。

09-25 22:30
查看更多