c# - 使用后台 worker 单击了哪个按钮

标签 c# backgroundworker

<分区>

我有几个按钮可以使用后台工作程序做一些事情。我想知道点击了哪个按钮,所以我这样做了:

public MyClass()
{
    _worker.DoWork += worker_DoWork;
    _worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    _worker.ProgressChanged += worker_ProgressChanged;
    _worker.WorkerReportsProgress = true;
}

private void First_Button_Click(object sender, RoutedEventArgs e)
{
    _worker.RunWorkerAsync();
}

private void Second_Button_Click(object sender, RoutedEventArgs e)
{
    _worker.RunWorkerAsync();
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    Button clickedButton = (Button)sender;
    switch (clickedButton.Name)
    {
        case "First_Button":
            directory = _ftp.GetCurrentDate(true);
            break;
        case "Second_Button":
            directory = _ftp.GetCurrentDate(false);
            break;
        case null:
            return;
    }
}

当我单击其中一个按钮时,我得到 System.InvalidCastException: Unable to cast object of type 'System.ComponentModel.BackgroundWorker' to type 'System.Windows.Controls.Button' 。

我知道线程安全调用的重要性,并且我之前在 this site 的帮助下完成了这项工作,但我不知道如何处理这个问题。请帮忙。

最佳答案

sender 参数是引发事件的对象,因此在您的情况下它将是一个 BackgroundWorker 对象,而不是一个 Button .这就是该转换失败的原因。

您可以使用接受对象的重载将按钮名称传递给后台工作程序。然后可以在 DoWork 事件中使用它。

例如:

private void First_Button_Click(object sender, RoutedEventArgs e)
{
    _worker.RunWorkerAsync("First_Button");
}

private void Second_Button_Click(object sender, RoutedEventArgs e)
{
    _worker.RunWorkerAsync("Second_Button");
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    string buttonName = (string)e.Argument;

    switch (buttonName)
    {
        case "First_Button":
            directory = _ftp.GetCurrentDate(true);
            break;
        case "Second_Button":
            directory = _ftp.GetCurrentDate(false);
            break;
        case null:
            return;
    }
}

只是想一想,我总是发现为后台工作人员参数创建一个专用类是个好主意,这样您就可以在需要时轻松传递多个值。

关于c# - 使用后台 worker 单击了哪个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32137177/

相关文章:

c# - 在 C# 中,^ 字符有什么作用?

wpf - 使用带有 MVVM 模式的 WPF 实现进度条(使用 BackgroundWorker)

c# - 带有 ProgressBar 的 BackgroundWorker - 跨线程操作无效

c# - 调度程序的种类

c# - 如何处理空字符串?

c# - 如何避免通过winform向表中输入重复值?

c# - 快速访问在 C# 中包含属性的类型/方法/...

c# - 后台工作人员在指定时间后停止工作

c# - MVC3 应用程序中的 BackgroundWorker 卡住 UI

c# - 从 C# 中的另一个窗体更新组合框