场景_1。
1.用户。按下“开始”按钮;
2.程序。在“ flowLayoutPanel1”中创建用户元素“ ucBackgroundWorker”的实例;
3.程序。在“ treeView1”中创建一个节点;
“ Scenario_1”可以无限次重复。
场景_2。
有:
-在“ flowLayoutPanel1”中启动了多个过程;
-在“ treeView1”中有一棵进程树;
场景:
1.用户。将光标移动到“ treeView1”;
2.程序。在“ flowLayoutPanel2”中,显示流程(实例
光标所在节点的“ ucBackgroundWorker”“);
据我了解,我尝试实施此方案(方案_1 +方案_2)。
我以为可以为用户元素实例分配索引,
然后根据索引显示在“ flowLayoutPanel2”中。
为了进行测试,该脚本的按钮创建了一个按钮“ btShowTheProces”
但是该项目不起作用。
调试时出现错误。
Form3.cs
flowLayoutPanel1.Controls.Add (ucBgWorker [i_ucBWrk]);
错误“对象引用未指向该对象的实例。”
ucBgWorker = null;
您的问题
1.如何解决错误?
2.我可以正确解决我的问题吗?
3.完成此方案的其他方法有哪些?
例如,该过程不是绑定到索引,而是绑定到“字符串”吗?
例如,类似这样的
string i_ucBWrk;
i_ucBWrk = "process_1";
flowLayoutPanel1.Controls.Add (ucBgWorker [i_ucBWrk]);
Form3.cs
命名空间rsh { 公共局部类Form3:表单 { // ucBackgroundWorker [] ucBgWorker = null;
int i_ucBWrk=0;
private ucBackgroundWorker[] ucBgWorker;
int procNumb;
public Form3()
{
InitializeComponent();
}
// после выбора узла дерева
void treeView1_AfterSelect(object sender, TreeViewCancelEventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
i_ucBWrk++;
ucBgWorker[i_ucBWrk] = new ucBackgroundWorker();
// ucBgWorker[i_ucBWrk].Done += new Action<string, EventArgs>(Worker_Done);
// ucBgWorker[i_ucBWrk].Cancel += new Action<string, EventArgs>(Worker_Cancel);
flowLayoutPanel1.Controls.Add(ucBgWorker[i_ucBWrk]);
ucBgWorker[i_ucBWrk].Run(1);
// ucBgWorker.Run(Convert.ToInt32(textBox1.Text));
}
void Worker_Done(string arg, EventArgs evtarg)
{
label1.Text = arg + " Done One";
//System.Threading.Thread.Sleep(1000);
}
void Worker_Cancel(string arg, EventArgs evtarg)
{
label1.Text = arg + " Cancel Click";
//System.Threading.Thread.Sleep(1000);
}
// show the process
private void btShowTheProces_Click(object sender, EventArgs e)
{
procNumb = Convert.ToInt32(numericUpDown1.Value);
flowLayoutPanel2.Controls.Clear();
flowLayoutPanel2.Controls.Add(ucBgWorker[procNumb]);
}
}
}
ucBackgroundWorker.cs
namespace rsh
{
public partial class ucBackgroundWorker : UserControl
{
BackgroundWorker bgWorker = null;
public event Action<string, EventArgs> Done;
public event Action<string, EventArgs> Cancel;
private static bool m_continue = true;
// Уведомляет один или более ожидающих потоков о том, что произошло событие. Этот класс не наследуется.
// https://msdn.microsoft.com/ru-ru/library/system.threading.manualresetevent(v=vs.110).aspx
private ManualResetEvent _resetEvent = new ManualResetEvent(false);
//Semaphore sWaiter = new Semaphore(0, 1);
public ucBackgroundWorker()
{
InitializeComponent();
bgWorker = new BackgroundWorker();
bgWorker.WorkerSupportsCancellation = true;
bgWorker.WorkerReportsProgress = true;
bgWorker.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
bgWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
public void Run(int counter)
{
if (!bgWorker.IsBusy)
{
bgWorker.RunWorkerAsync(counter);
}
_resetEvent.Set();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int input = int.Parse(e.Argument.ToString());
this.BeginInvoke((MethodInvoker)delegate
{
lblStatus.Text = "Running";
});
for (int i = 1; i <= input; i++)
{
_resetEvent.WaitOne();
Thread.Sleep(1000);
(sender as BackgroundWorker).ReportProgress(i*1); // шаг
// (sender as BackgroundWorker).ReportProgress(i * 10);
if ((sender as BackgroundWorker).CancellationPending)
{
this.BeginInvoke((MethodInvoker)delegate
{
lblStatus.Text = "Cancel";
});
e.Cancel = true;
return;
}
}
Thread.Sleep(1000);
}
// This event handler deals with the results of the
// background operation.
// Этот обработчик событий имеет дело с результатами
// фоновая операция.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
// Сначала обрабатываем случай, когда было создано исключение.
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
if (Cancel != null)
Cancel(this.Name, EventArgs.Empty);
}
else
{
this.BeginInvoke((MethodInvoker)delegate
{
lblStatus.Text = "Done";
});
if (Done != null)
Done(this.Name, EventArgs.Empty);
}
_resetEvent.Reset();
}
// This event handler updates the progress bar.
// Этот обработчик событий обновляет индикатор выполнения.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pBar.Refresh();
pBar.Value = e.ProgressPercentage;
}
// *** *** *** ***
// *** КНОПКИ ***
// *** *** *** ***
// Cancel
private void btnCancel_Click(object sender, EventArgs e)
{
if (bgWorker.IsBusy)
{
bgWorker.CancelAsync();
}
}
// Pause
private void btnPause_Click(object sender, EventArgs e)
{
if (bgWorker.IsBusy)
{
if (btnPause.Text.ToUpper() == "PAUSE")
{
btnPause.Text = "Resume";
m_continue = false;
_resetEvent.Reset();
}
else
if (btnPause.Text.ToUpper() == "RESUME")
{
btnPause.Text = "Pause";
m_continue = true;
_resetEvent.Set();
}
}
}
}
}
项目-link
答案 0 :(得分:3)
您永远不会初始化ucBgWorker数组。
将代码更改为此
private ucBackgroundWorker[] ucBgWorker = new ucBackgroundWorker[10];
与此有关的问题是,然后将您的数组设置为最大10。
最好使用列表:
private List<ucBackgroundWorker> ucBgWorker = new List<ucBackgroundWorker>();
添加以下项目:
ucBgWorker.Add(new ucBackgroundWorker());
您仍然可以按索引访问项目:
ucBackgroundWorker item = ucBgWorker[0];
只要列表中有项目。