c# - 带参数调用委托(delegate)方法名

标签 c# multithreading winforms

尝试进行设置,让 BackgroundWorker 在后台运行,然后在完成每个步骤时在单独的模式对话框上更新其进度。当然,问题是尝试从 BackgroundWorker 线程更新进度对话框会导致跨线程问题。

代码:(有问题的行有用 *** 包围的注释)

public void StartProcess()
{
    // dialog that shows a simple marquee progress bar and a message
    ProgressDialog progress = new ProgressDialog("Starting operation...");

    // create background worker thread
    BackgroundWorker bw = new BackgroundWorker();
    bw.WorkerSupportsCancellation = true;
    bw.WorkerReportsProgress = true;
    bw.DoWork += Bw_DoWork;
    bw.RunWorkerCompleted += Bw_RunWorkerCompleted;

    if(!bw.IsBusy)
    {
        bw.RunWorkerAsync();
        progress.ShowDialog();
    }
}

private void Bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker bw = sender as BackgroundWorker;
    if(bw.CancellationPending)
    {
        e.Cancel = true;
    }
    else
    {
        // perform step 1

        // *** this line generates cross-thread problems ***
        progress.Message = "Performing step 2...";

        // etc...
    }
}

这是进度对话框的代码:

public partial class ProgressDialog : Form
{
    public string Message
    {
        get
        {
            return lblMessage.Text;
        }
        set
        {
            if(lblMessage.InvokeRequired)
            {
                // *** not sure how to invoke this by passing the "value" parameter ***
                // *** returns a TargetParameterCountException ***
                // *** trying to pass "value" in results in "Method name expected" error ***
                lblMessage.Invoke(new UpdateMessageDelegate(SetMessage));
            }
        }
    }

    private delegate void UpdateMessageDelegate(string s);

    private void SetMessage(string s)
    {
        lblMessage.Text = s;
    }
}

如何使用标签的 set 方法和隐式 value 参数安全地更改标签的文本值?

最佳答案

尝试这样调用它:

lblMessage.Invoke((Action)(() => SetMessage(value)));

然后您还可以避免创建私有(private) UpdateMessageDelegate 委托(delegate)。

关于c# - 带参数调用委托(delegate)方法名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166275/

相关文章:

ios - iOS Moya Web服务: make one call wait for all others to finish,然后阻止新调用

c# - 打印未从页面的上边缘开始

c# - 在 ToolStripMenuItem 中捕获 mouseClick 和 KeyDown 事件

c# - 为什么我们不能更改 ThreadPool 线程的单元状态,为什么我们在使用 ShowDialog 时不需要消息泵?

c# - 如何每秒更改表单元素的值?

c# - 树阵列到站点地图

c# - 什么是 base..ctor();在 C# 中?

c# - 在 Program.cs 中读取和使用 appsettings.json?

c# - 在 C# 中为循环中的方法创建线程

multithreading - 跨线程的异常传播?