如何在forloop中为每个interation运行BackgroundWorker进程?

时间:2016-10-27 10:21:10

标签: c# backgroundworker

如何在每个循环中正确使用我的代码?

仅执行一次的原始代码完美无缺 -

Form1.cs的

private void CreateUserClick(object sender, RoutedEventArgs e)       
    {

            User parameters = new User
            {
                user = UserTextBox.Text + i,                         
            };


            DataWorkers.InitiateWork(sender, DataWorkers.CreateUserWorker, parameters);
        }
    }

代码更改在forloop中执行CreateUserWork 5次,这将保存username

Form1.cs的

private void CreateUserClick(object sender, RoutedEventArgs e)       
{
    for (int i = 0; i < 5; i++)
    {                    
        User parameters = new User
        {
            user = UserTextBox.Text + i,                         
        };

        BackgroundWorker CreateUserWorker = new BackgroundWorker();

        CreateUserWorker.DoWork += new DoWorkEventHandler(Workers.CreateUserWork);

        DataWorkers.InitiateWork(sender, DataWorkers.CreateUserWorker, parameters);
    }
}

DataWorkers.cs

public class DataWorkers
{
    public static readonly BackgroundWorker CreateUserWorker = new BackgroundWorker();

    public static void StartUpLogic()
    {
        CreateAccountWorker.DoWork += CreateUserWork;
    }

    public static void InitiateWork(
        object sender,
        BackgroundWorker worker,
        WorkerParameters parameters = null)
    {
        StaticElements.InvokerButtons[worker] = new InvokerButton(sender);

        StaticElements.InvokerButtons[worker].Button.IsEnabled = false;
        StaticElements.InvokerButtons[worker].Button.Content = "Wait...";

        worker.RunWorkerAsync(parameters);
    }
}

public static void CreateUserWork(object sender, DoWorkEventArgs e)
        {
//create new user
}

建议我正确的改变。

1 个答案:

答案 0 :(得分:2)

尝试在没有后台工作者的情况下解决此问题。

private async void CreateUserClick(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < 5; i++)
    {
        User parameters = new User
        {
            user = UserTextBox.Text + i,
        };

        await Task.Run(()=>CreateUserWork(parameters));
    }
}

其中

CreateUserWork(User parameters)
{ 
 // your saving stuff
}