c#将参数传递给Action

时间:2013-10-04 02:52:00

标签: c# multithreading winforms backgroundworker

我有以下代码:

public partial class WaitScreen : Form
{
    public Action Worker { get; set; }

    public WaitScreen(Action worker)
    {
        InitializeComponent();

        if (worker == null)
            throw new ArgumentNullException();

        Worker = worker;
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
    }
}

这是消费者的代码:

private void someButton_Click(object sender, EventArgs e)
{
    using (var waitScreen = new WaitScreen(SomeWorker))
        waitScreen.ShowDialog(this);
}

private void SomeWorker()
{
    // Load stuff from the database and store it in local variables.
    // Remember, this is running on a background thread and not the UI thread, don't touch controls.
}

现在,我必须为Action“SomeWorker”添加一个参数,例如:

private void SomeWorker(Guid uid, String text)
    {
        // here will execute the task!!
    }

如何将参数 uid 文字传递给动作?

是否可以将其设为通用,以便我可以传递任何参数,以便它可以使用任何数量和类型的参数?

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

Action定义为delegate void Action()。因此,您无法将变量传递给它。

你想要的是Action<T, T2>,它公开了两个要传入的参数。

使用示例..随意应用于您自己的需求:

Action<Guid, string> action = (guid, str) => {
    // guid is a Guid, str is a string.
};


// usage
action(Guid.NewGuid(), "Hello World!");

答案 1 :(得分:1)

对于这种情况,我认为您不能使用Action<Guid, string>,因为我无法看到您如何将参数传递到新表单中。您最好的选择是使用匿名委托来捕获您想要传入的变量。您仍然可以将该功能保持独立,但您需要匿名委托进行捕获。

private void someButton_Click(object sender, EventArgs e)
{
    var uid = Guid.NewGuid();
    var text = someTextControl.Text;

    Action act = () => 
        {
            //The two values get captured here and get passed in when 
            //the function is called. Be sure not to modify uid or text later 
            //in the someButton_Click method as those changes will propagate.
            SomeWorker(uid, text)
        }
    using (var waitScreen = new WaitScreen(act))
        waitScreen.ShowDialog(this);
}

private void SomeWorker(Guid uid, String text)
{
    // Load stuff from the database and store it in local variables.
    // Remember, this is running on a background thread and not the UI thread, don't touch controls.
}