情景:
我有一个窗口表单,其中包含DataGridWiew
个3个预定义列。
我在函数外部声明了3个变量并分配到函数内部。
我有一个枚举东西的函数,并将它放在3列中,逐行:
string VARIABLE1;
string VARIABLE2;
string VARIABLE3;
private void FunctionEnumerateStuff()
{
foreach (StuffObject STUFF in StuffCollection)
{
VARIABLE1 = STUFF.SubStuff1.ToString();
VARIABLE2 = STUFF.SubStuff2.ToString();
VARIABLE3 = STUFF.SubStuff3.ToString();
DatagridWiew1.Rows.Add(VALUE1, VALUE2, VALUE3);
}
}
我想要做的是从BackGroundWorker
进程执行此功能,以便应用程序的GUI流畅且响应迅速。
我已经阅读了背景工作者,但我遇到了麻烦,因为所有的例子似乎都是完全不同的情况,而且大多数情况都非常复杂。
一些有用的教育灵魂可以帮助我和其他人提供一个非常基本的例子,说明如何以最简单的方式使其工作。 感谢。
答案 0 :(得分:1)
我会使用这样的东西(非常粗略和未经测试):
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
var list = new List<SomeRowType>();
foreach (StuffObject STUFF in StuffCollection)
{
VARIABLE1 = STUFF.SubStuff1.ToString();
VARIABLE2 = STUFF.SubStuff2.ToString();
VARIABLE3 = STUFF.SubStuff3.ToString();
//DatagridWiew1.Rows.Add(VALUE1, VALUE2, VALUE3);
list.Add(new SomeRowType(VALUE1, VALUE2, VALUE3)); //probably meant: VARIABLEn
}
e.Result = list;
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
}
else
{
var list = (List<SomeRowType>)e.Result;
DatagridWiew1.DataSource = list;
}
}
答案 1 :(得分:1)
以下是一个例子:
class Form1 : Form
{
private BackgroundWorker Worker { get; set; }
public Form1()
{
Worker = new BackgroundWorker();
Worker.WorkerSupportsCancellation = true;
Worker.DoWork += OnWorkerDoWork;
Worker.RunWorkerCompleted += OnWorkerRunWorkerCompleted;
// at some point start the worker.
Worker.RunWorkerAsync();
}
void OnWorkerDoWork(object sender, RunWorkerCompletedEventArgs e)
{
foreach(var data in someData)
{
// if cancelled
if (e.Cancelled)
return;
AddDataToColumn(someData.Var1, someData, Var2, someData.Var3);
}
}
void OnWorkerRunWorkerCompleted(object sender, DoWorkEventArgs e)
{
}
private delegate void AddDataToColumnDelegate(string var1, string var2, string var3);
private void AddDataToColumn(string var1, string var2, string var3)
{
// check if cross-thread operation
if (InvokeRequired)
{
Invoke(new AddDataToColumnDelegate(AddDataToColumn), var1, var2, var3);
return;
}
// Add data to column
dataGridView1.Rows.Add(var1, var2, var3);
}
}