倒立的后台工作者

发布于 2024-11-27 14:28:13 字数 1432 浏览 2 评论 0原文

我有许多类可以完成一些工作,通常是单步执行记录集并为每条记录调用一个或两个 Web 服务。

目前,这一切都在 GUI 线程中运行并挂起绘画。第一个想法是使用BackgroundWorker 并实现一个漂亮的进度条、处理错误、完成等。Background Worker 可以实现所有美好的事情。

代码一出现在屏幕上,它就开始散发出气味。我在每个类中编写了很多后台工作人员,在 bw_DoWork 方法中重复了大部分 ProcessRows 方法,并认为应该有更好的方法,而且可能已经完成了。

在我继续重新发明轮子之前,是否有一个类的模式或实现可以将后台工作人员分开?它需要实现 ibackgroundable 等接口的类,但这些类仍然可以独立运行,并且需要最少的更改来实现该接口。

编辑:@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();
    }

我可以继续这样做,但不想重新发明。

我正在寻找的答案将类似于“是的,Joe 对此做了很好的实现(此处)”或“这是一个代理小部件模式,请阅读它(此处)”

I have a number of classes that do stuff, typically step through a recordset and call a webservice or two for each record.

At the moment this all runs in the GUI thread and hangs painting. First thought was to use a BackgroundWorker and implement a nice progress bar, handle errors, completion etc. All the nice things a Background worker enables.

As soon as the code hit the screen it started to smell. I was writing a lot of the background worker into each class, repeating most of the ProcessRows method in a bw_DoWork method and thinking there should be a better way, and it's probably already been done.

Before I go ahead and reinvent the wheel is there a pattern or implementation for a class that seperates out the background worker? It would take classes that implement an interface such as ibackgroundable, but the classes could still be run standalone, and would require minimal change to implement the interface.

Edit: A simplified example requested by @Henk:

I have:

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

I think I want:

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

I could go ahead and do this, but don't want to reinvent.

The answer I'm looking for would along the lines of "Yes, Joe did a good implementation of that (here)" or "That's a Proxy Widget pattern, go read about it (here)"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白鸥掠海 2024-12-04 14:28:13

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

/// <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() 移动到它自己的类中,并实现取消操作的方法。

Each operation needs to implement the following 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; }
}

This seperates the enumeration of the steps from the processing.

Here is a sample operation:

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

This can be called from the form like this:

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

I haven't done it yet but I'll be moving BackgroundOperation() into a class of its own and implementing the method to cancel the operation.

日久见人心 2024-12-04 14:28:13

我会将非 UI 代码放入一个新类中并使用线程(而不是后台工作者)。要显示进度,请将新类触发事件返回 UI 并使用 Dispatcher.Invoke 更新 UI。

其中有一些编码,但它更干净并且有效。并且比使用后台工作人员更易于维护(这仅适用于小任务)。

I would put my non-UI code into a new class and use a Thread (not background worker). To show progress, have the new class fire events back to the UI and use Dispatcher.Invoke to update the UI.

There is a bit of coding in this, but it is cleaner and works. And is more maintainable than using background worker (which is only really intended for small tasks).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文