此BackgroundWorker当前正忙,无法在循环c#中同时运行多个任务 [英] This BackgroundWorker is currently busy and cannot run multiple tasks concurrently inside for loop c#
问题描述
如果我单击一次for循环内多次启动backgroundworker的按钮,则会收到此错误.
I get this error if I click a button that starts the backgroundworker multiple times inside for loop.
{"This BackgroundWorker is currently busy and cannot run multiple tasks
concurrently."}
如何在每个循环中正确地运行我的代码?
How do I work my code properly in each and every loop ?
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(DataWorkers.CreateUserWork);
DataWorkers.InitiateWork(sender, CreateUserWorker, parameters);
}
}
DataWorkers.cs
DataWorkers.cs
public class DataWorkers
{
public static readonly BackgroundWorker CreateUserWorker = new BackgroundWorker();
public static void HookUpWorkersLogic()
{
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);
}
}
我已经在下面的forloop中进行了此更改,但此更改后仍未唤醒,也未获得任何异常,但应用程序挂起了
I have made this change below in forloop, but still not wokring nor getting any exception after this change but application hangs up
BackgroundWorker createUserWorker = new BackgroundWorker();
createUserWorker.DoWork += new DoWorkEventHandler(DataWorkers.CreateUserWork);
DataWorkers.InitiateWork(sender, createUserWorker, parameters);
SE
SE
推荐答案
您不应多次启动同一BackgroundWorker实例.在循环内创建一个新实例,或者更好地启动在后台(线程池)线程上执行工作的新任务:
You should not start the same BackgroundWorker instance more than once. Create a new instance inside the loop or better yet start new tasks that perform the work on a background (thread pool) thread:
private void CreateUserClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 5; i++)
{
User parameters = new User
{
user = UserTextBox.Text + i,
};
Task.Factory.StartNew(()=>
{
//do your thing...
});
}
}
如果您需要其他帮助,请将问题的可复制示例上载到OneDrive,并在此处发布链接.
Please upload a reproducible sample of your issue to OneDrive and post the link to it here if you need any further help.
希望有帮助.
请记住,通过将有用的帖子标记为答案来关闭话题,然后在遇到新问题时开始新话题.请不要在同一线程中问几个问题.
Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.
这篇关于此BackgroundWorker当前正忙,无法在循环c#中同时运行多个任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!