C# 2008

我正在使用下面的代码登录到软电话。然而,登录过程是一个漫长的过程,因为有很多东西需要初始化和检查,我在这里只放了一些,因为它会使代码很长才能发布。

在下面的代码中,在执行每次检查之前,我正在检查 CancellationPending 是否在我的取消按钮单击事件中调用了 CancelAsync。这样对吗?此外,如果检查失败,我也会调用 CancelAsync 并将 e.Cancel 设置为 true。

我想知道我在这里使用的方法是否是最好的使用方法。

非常感谢您的任何建议,

private void bgwProcessLogin_DoWork(object sender, DoWorkEventArgs e)
    {
        /*
         * Perform at test to see if the background worker has been
         * cancelled by the user before attemping to continue to login.
         *
         * Cancel background worker on any failed attemp to login
         */

        // Start with cancel being false as to reset this if cancel has been set to true
        // in the cancel button.
        e.Cancel = false;

        NetworkingTest connection_test = new NetworkingTest();
        if (!this.bgwProcessLogin.CancellationPending)
        {
            // Check local LAN or Wireless connection
            if (!connection_test.IsNetworkConnected())
            {
                // Update label
                if (this.lblRegistering.InvokeRequired)
                {
                    this.lblRegistering.Invoke(new UpdateRegisterLabelDelegate(UpdateRegisterLabel), "No network connection");
                }
                else
                {
                    this.lblRegistering.Text = "No network connection";
                }
                // Failed attemp
                this.bgwProcessLogin.CancelAsync();
                e.Cancel = true;
                return;
            }
            // Report current progress
            this.bgwProcessLogin.ReportProgress(0, "Network connected");
        }
        else
        {
            // User cancelled
            e.Cancel = true;
            return;
        }

        // Test if access to Server is available
        if (!this.bgwProcessLogin.CancellationPending)
        {
            if (!connection_test.IsSIPServerAvailable())
            {
                // Update label
                if (this.lblRegistering.InvokeRequired)
                {
                    this.lblRegistering.Invoke(new UpdateRegisterLabelDelegate(UpdateRegisterLabel), "Server unavailable");
                }
                else
                {
                    this.lblRegistering.Text = "Server unavailable";
                }
                // Failed attemp
                this.bgwProcessLogin.CancelAsync();
                e.Cancel = true;
                return;
            }
            // Report current progress
            this.bgwProcessLogin.ReportProgress(1, "Server available");
        }
        else
        {
            // User cancelled
            e.Cancel = true;
            return;
        }
        .
        .
        .
}


 private void bgwProcessLogin_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // Check for any errors
        if (e.Error == null)
        {
            if (e.Cancelled)
            {
                // User cancelled login or login failed
            }
            else
            {
                // Login completed successfully
            }
        }
        else
        {
            // Something failed display error
            this.statusDisplay1.CallStatus = e.Error.Message;
        }
    }


 private void bgwProcessLogin_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        this.lblRegistering.Text = e.UserState.ToString();
    }

private void btnCancel_Click(object sender, EventArgs e)
    {
        // Cancel the logging in process
        this.bgwProcessLogin.CancelAsync();
        this.lblRegistering.Text = "Logged out";
}

最佳答案

可能只有一个问题:如果 DoWork 事件处理程序中的某个操作会持续很长时间。在这种情况下,您只能在该操作完成后中止挂起的操作。如果 DoWork 事件中的所有操作都不能持续很长时间(例如,不超过 5 秒),则一切正常,但是如果其中一个操作可以持续很长时间(例如,5 分钟),在这种情况下用户有等待此操作完成。

如果 DoWork 包含持久操作,您可以使用类似 AbortableBackgroundWorker 的东西。像这样的东西:

public class AbortableBackgroundWorker : BackgroundWorker
{
    private Thread workerThread;

    protected override void OnDoWork(DoWorkEventArgs e)
    {
        workerThread = Thread.CurrentThread;
        try
        {
            base.OnDoWork(e);
        }
        catch (ThreadAbortException)
        {
            e.Cancel = true; //We must set Cancel property to true!
            Thread.ResetAbort(); //Prevents ThreadAbortException propagation
        }
    }


    public void Abort()
    {
        if (workerThread != null)
        {
            workerThread.Abort();
            workerThread = null;
        }
    }
}

在这种情况下,您可以真正中止挂起的操作,但您也有一些限制(有关中止托管线程的更多信息和一些限制,请参阅 Plumbing the Depths of the ThreadAbortException Using Rotor )。

附言我同意 Oliver 的观点,即您应该以更实用的形式包装 InvokeRequired。

关于C#取消后台 worker 的DoWork,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/826096/

10-13 02:06