欢迎光临
我们一直在努力

利用 Visual C# 创作简单的多线程组件(转载于MSDN)-.NET教程,C#语言

建站超值云服务器,限时71元/月

可以编写能同时执行多个任务的应用程序。此能力(称为“多线程处理”或“自由线程处理”)是设计处理器密集型且要求用户输入的组件的强大方法。计算工资表信息的组件就是一个可能利用多线程处理的组件示例。该组件可以在一个线程上处理用户输入到数据库的数据,而在另一个线程上执行频繁使用处理器的工资表计算。通过在不同的线程上运行这些进程,用户不必等到计算机完成计算,就可以输入其他数据。在本演练中,将创建一个简单的多线程组件,该组件可以同时执行若干个复杂计算。

创建项目

应用程序将包括单个窗体和一个组件。用户将输入值并指示该组件开始计算。然后,窗体将接收来自该组件的值,将其显示在标签控件中。该组件将执行频繁使用处理器的计算,并在完成后通知窗体。您将在组件中创建公共变量,用以保存从用户界面收到的值。同时,您还将在组件中实现一些方法,根据这些变量的值执行计算。

注意 尽管对于计算值的方法来说,函数通常更为可取,但不能在线程之间传递参数,也不能返回值。有很多向线程提供值和从线程接收值的简单方法。在本演示中,将通过更新公共变量将值返回到用户界面,当线程执行完毕后,使用事件来通知主程序。

创建窗体

创建新的“windows 应用程序”项目。

将应用程序命名为 calculations,并将 form1.cs 重命名为 frmcalculations.cs。

该窗体将用作应用程序的主用户界面。

双击设计器上的窗体以打开代码编辑器。在“编辑”菜单中,选择“查找和替换”,然后选择“替换”。使用“全部替换”将 form1 替换为 frmcalculations。

在“解决方案资源管理器”中,右击“frmcalculations.cs”并选择“视图设计器”。设计器打开。

向窗体中添加 5 个 label 控件、4 个 button 控件和 1 个 textbox 控件。

为这些控件设置属性,如下所示:

控件 名称 文本

label1 lblfactorial1 (空白)

label2 lblfactorial2 (空白)

label3 lbladdtwo (空白)

label4 lblrunloops (空白)

label5 lbltotalcalculations (空白)

button1 btnfactorial1 factorial

button2 btnfactorial2 factorial – 1

button3 btnaddtwo add two

button4 btnrunloops run a loop

textbox1 txtvalue (空白)

创建 calculator 组件

从“项目”菜单中选择“添加组件”。

将组件命名为 calculator。

向 calculator 组件添加公共变量

为 calculator 打开代码编辑器。

添加创建公共变量的语句,这些变量用于将值从 frmcalculations 传递给每个线程。

变量 vartotalcalculations 将保留该组件执行的计算总数的累计值,而其他变量将接收来自窗体的值。

public int varaddtwo;

public int varfact1;

public int varfact2;

public int varloopvalue;

public double vartotalcalculations = 0;

向 calculator 组件添加方法和事件

为事件声明委托,组件将使用这些事件向窗体传递值。

注意 尽管您将声明 4 个事件,但由于其中的两个事件将具有相同的签名,因此只需要创建 3 个委托。

紧接着上一步输入的变量声明的下方,键入下列代码:

// this delegate will be invoked with two of your events.

public delegate void factorialcompletehandler(double factorial, double totalcalculations);

public delegate void addtwocompletehandler(int result, double totalcalculations);

public delegate void loopcompletehandler(double totalcalculations, int counter);

声明组件将用来与应用程序进行通信的事件。为实现此目的,紧接着上一步输入的代码的下方,添加下列代码。

public event factorialcompletehandler factorialcomplete;

public event factorialcompletehandler factorialminusonecomplete;

public event addtwocompletehandler addtwocomplete;

public event loopcompletehandler loopcomplete;

紧接着上一步键入的代码的下方,键入下列代码:

// this method will calculate the value of a number minus 1 factorial

// (varfact2-1!).

public void factorialminusone()

{

double vartotalasofnow = 0;

double varresult = 1;

// performs a factorial calculation on varfact2 – 1.

for (int varx = 1; varx <= varfact2 – 1; varx++)

{

varresult *= varx;

// increments vartotalcalculations and keeps track of the current

// total as of this instant.

vartotalcalculations += 1;

vartotalasofnow = vartotalcalculations;

}

// signals that the method has completed, and communicates the

// result and a value of total calculations performed up to this

// point.

factorialminusonecomplete(varresult, vartotalasofnow);

}

// this method will calculate the value of a number factorial.

// (varfact1!)

public void factorial()

{

double varresult = 1;

double vartotalasofnow = 0;

for (int varx = 1; varx <= varfact1; varx++)

{

varresult *= varx;

vartotalcalculations += 1;

vartotalasofnow = vartotalcalculations;

}

factorialcomplete(varresult, vartotalasofnow);

}

// this method will add two to a number (varaddtwo+2).

public void addtwo()

{

double vartotalasofnow = 0;

int varresult = varaddtwo + 2;

vartotalcalculations += 1;

vartotalasofnow = vartotalcalculations;

addtwocomplete(varresult, vartotalasofnow);

}

// this method will run a loop with a nested loop varloopvalue times.

public void runaloop()

{

int varx;

double vartotalasofnow = 0;

for (varx = 1; varx <= varloopvalue; varx++)

{

// this nested loop is added solely for the purpose of slowing down

// the program and creating a processor-intensive application.

for (int vary = 1; vary <= 500; vary++)

{

vartotalcalculations += 1;

vartotalasofnow = vartotalcalculations;

}

}

loopcomplete(vartotalasofnow, varloopvalue);

}

将用户输入传输到组件

下一步是向 frmcalculations 添加代码,以接收用户输入,以及从 calculator 组件接收值和向它传输值。

实现 frmcalculations 的前端功能

在代码编辑器中打开 frmcalculations。

找到 public class frmcalculations 语句。紧接着 { 的下方键入:

calculator calculator1;

找到构造函数。紧接着 } 之前,添加以下行:

// creates a new instance of calculator.

calculator1 = new calculator();

在设计器中单击每个按钮,为每个控件的单击事件处理程序生成代码大纲,并添加代码以创建这些处理程序。

完成后,单击事件处理程序应该类似于以下形式:

private void btnfactorial1_click(object sender, system.eventargs e)

// passes the value typed in the txtvalue to calculator.varfact1.

{

calculator1.varfact1 = int.parse(txtvalue.text);

// disables the btnfactorial1 until this calculation is complete.

btnfactorial1.enabled = false;

calculator1.factorial();

}

private void btnfactorial2_click(object sender, system.eventargs e)

{

calculator1.varfact2 = int.parse(txtvalue.text);

btnfactorial2.enabled = false;

calculator1.factorialminusone();

}

private void btnaddtwo_click(object sender, system.eventargs e)

{

calculator1.varaddtwo = int.parse(txtvalue.text);

btnaddtwo.enabled = false;

calculator1.addtwo();

}

private void btnrunloops_click(object sender, system.eventargs e)

{

calculator1.varloopvalue = int.parse(txtvalue.text);

btnrunloops.enabled = false;

// lets the user know that a loop is running

lblrunloops.text = "looping";

calculator1.runaloop();

}

在上一步添加的代码的下方,键入以下代码以处理窗体将从 calculator1 接收的事件:

protected void factorialhandler(double value, double calculations)

// displays the returned value in the appropriate label.

{

lblfactorial1.text = value.tostring();

// re-enables the button so it can be used again.

btnfactorial1.enabled = true;

// updates the label that displays the total calculations performed

lbltotalcalculations.text = "totalcalculations are " +

calculations.tostring();

}

protected void factorialminushandler(double value, double calculations)

{

lblfactorial2.text = value.tostring();

btnfactorial2.enabled = true;

lbltotalcalculations.text = "totalcalculations are " +

calculations.tostring();

}

protected void addtwohandler(int value, double calculations)

{

lbladdtwo.text = value.tostring();

btnaddtwo.enabled = true;

lbltotalcalculations.text = "totalcalculations are " +

calculations.tostring();

}

protected void loopdonehandler(double calculations, int count)

{

btnrunloops.enabled = true;

lblrunloops.text = count.tostring();

lbltotalcalculations.text = "totalcalculations are " +

calculations.tostring();

}

在 frmcalculations 的构造函数中,紧挨在 } 之前添加下列代码,以处理窗体将从 calculator1 接收的自定义事件:

calculator1.factorialcomplete += new

calculator.factorialcompletehandler(this.factorialhandler);

calculator1.factorialminusonecomplete += new

calculator.factorialcompletehandler(this.factorialminushandler);

calculator1.addtwocomplete += new

calculator.addtwocompletehandler(this.addtwohandler);

calculator1.loopcomplete += new

calculator.loopcompletehandler(this.loopdonehandler);

测试应用程序

现在项目已经创建完毕,该项目将能够执行若干个复杂计算的组件与窗体结合在一起。尽管尚未实现多线程处理功能,但在继续之前应该对项目进行测试,以验证它的功能。

测试项目

从“调试”菜单中选择“启动”。

应用程序启动并显示 frmcalculations。

在文本框中键入 4,然后单击标记为“添加两个”的按钮。

在按钮下方的标签中应该显示数字“6”,在 lbltotalcalculations 中应该显示“total calculations are 1”。

现在单击标记为“阶乘 – 1”的按钮。

该按钮的下方应显示数字“6”,而 lbltotalcalculations 中现在应显示“total calculations are 4”。

将文本框中的值更改为 20,然后单击标记为“阶乘”的按钮。

该按钮的下方显示数字“2.43290200817664e+18”,而 lbltotalcalculations 中现在显示为“total calculations are 24”。

将文本框中的值更改为 50000,然后单击标记为“运行循环”的按钮。

注意,在此按钮重新启用前有一个短暂然而明显的间隔。此按钮下的标签应显示“50000”,而总的计算次数显示为“25000024”。

将文本框中的值更改为 5000000 并单击标记为“运行循环”的按钮,紧接着单击标记为“添加两个”的按钮。再次单击它。

直到循环已经完成,该按钮以及窗体上的任何控件才有响应。

如果程序只运行单个执行线程,则类似上述示例的频繁使用处理器的计算倾向于占用该程序,直到计算已经完成。在下一节中,您将向应用程序添加多线程处理功能,以便一次可以运行多个线程。

添加多线程处理功能

上面的示例演示了只运行单个执行线程的应用程序的限制。在下一节,您将使用 thread 类对象向组件添加多个执行线程。

添加 threads 子例程

在代码编辑器中打开 calculator.cs。

在代码顶部附近,找到类声明,紧接着 { 的下方,键入下列代码:

// declares the variables you will use to hold your thread objects.

public system.threading.thread factorialthread;

public system.threading.thread factorialminusonethread;

public system.threading.thread addtwothread;

public system.threading.thread loopthread;

在代码底部紧接着类声明结尾之前,添加以下方法:

public void choosethreads(int threadnumber)

{

// determines which thread to start based on the value it receives.

switch(threadnumber)

{

case 1:

// sets the thread using the addressof the subroutine where

// the thread will start.

factorialthread = new system.threading.thread(new

system.threading.threadstart(this.factorial));

// starts the thread.

factorialthread.start();

break;

case 2:

factorialminusonethread = new

system.threading.thread(new

system.threading.threadstart(this.factorialminusone));

factorialminusonethread.start();

break;

case 3:

addtwothread = new system.threading.thread(new

system.threading.threadstart(this.addtwo));

addtwothread.start();

break;

case 4:

loopthread = new system.threading.thread(new

system.threading.threadstart(this.runaloop));

loopthread.start();

break;

}

}

当实例化 thread 对象时,它要求一个 threadstart 对象形式的参数。threadstart 对象是一个指向开始线程的方法的地址的委托。threadstart 对象不能接受参数或者传递值,因此只能表示 void 方法。刚才实现的 choosethreads 方法将从调用它的程序接收一个值,并使用该值来确定要启动的适当线程。

向 frmcalculations 添加适当的代码

在代码编辑器中打开 frmcalculations.cs 文件,然后找到 protected void btnfactorial1_click。

注释掉直接调用 calculator1.factorial1 方法的行,如下所示:

// calculator1.factorial()

添加下列行,以调用 calculator1.choosethreads 方法:

// passes the value 1 to calculator1, thus directing it to start the

// correct thread.

calculator1.choosethreads(1);

对其他 button_click 子例程作类似的修改。

注意 一定要为 threads 参数包含适当的值。

完成后,代码看起来应该类似以下形式:

protected void btnfactorial1_click(object sender, system.eventargs e)

// passes the value typed in the txtvalue to calculator.varfact1

{

calculator1.varfact1 = int.parse(txtvalue.text);

// disables the btnfactorial1 until this calculation is complete

btnfactorial1.enabled = false;

// calculator1.factorial();

calculator1.choosethreads(1);

}

protected void btnfactorial2_click(object sender, system.eventargs e)

{

calculator1.varfact2 = int.parse(txtvalue.text);

btnfactorial2.enabled = false;

// calculator1.factorialminusone();

calculator1.choosethreads(2);

}

protected void btnaddtwo_click(object sender, system.eventargs e)

{

calculator1.varaddtwo = int.parse(txtvalue.text);

btnaddtwo.enabled = false;

// calculator1.addtwo();

calculator1.choosethreads(3);

}

protected void btnrunloops_click(object sender, system.eventargs e)

{

calculator1.varloopvalue = int.parse(txtvalue.text);

btnrunloops.enabled = false;

// lets the user know that a loop is running

lblrunloops.text = "looping";

// calculator1.runaloop();

calculator1.choosethreads(4);

}

封送处理对控件的调用

现在将加速窗体上的显示更新。鉴于控件总是由主执行线程所有,从属线程中对控件的任何调用都需要“封送处理”调用。封送处理是跨线程边界移动调用的行为,需要耗费大量的资源。为了使需要发生的封送处理量减到最少,并确保以线程安全方式处理调用,应使用 control.begininvoke 方法来调用主执行线程上的方法,从而使必须发生的跨线程边界的封送处理量减到最少。当调用操作控件的方法时,这种调用非常必要。有关详细信息,请参见从线程操作控件。

创建控件调用过程

为 frmcalculations 打开代码编辑器。在声明部分,添加下列代码:

public delegate void fhandler(double value, double calculations);

public delegate void a2handler(int value, double calculations);

public delegate void ldhandler(double calculations, int count);

invoke 和 begininvoke 需要将适当方法的委托作为参数。这些代码行声明一些委托签名,这些签名将被 begininvoke 用于调用适当的方法。

在代码中添加下列空方法。

public void facthandler(double value, double calculations)

{

}

public void fact1handler(double value, double calculations)

{

}

public void add2handler(int value, double calculations)

{

}

public void ldonehandler(double calculations, int count)

{

}

在“编辑”菜单中,使用“剪切”和“粘贴”,从 factorialhandler 方法中剪切所有代码,并将其粘贴到 facthandler 中。

对 factorialminushandler 和 fact1handler、addtwohandler 和 add2handler 以及 loopdonehandler 和 ldonehandler 重复上面的步骤。

完成后,在 factorialhandler、factorial1handler、addtwohandler 和 loopdonehandler 中应该没有剩余代码,并且它们曾经包含的所有代码应该已经移动到适当的新方法中。

调用 begininvoke 方法以异步调用这些方法。可以从窗体 (this) 或者窗体上的任何控件调用 begininvoke。

完成后,代码看起来应该类似以下形式:

protected void factorialhandler(double value, double calculations)

{

// begininvoke causes asynchronous execution to begin at the address

// specified by the delegate. simply put, it transfers execution of

// this method back to the main thread. any parameters required by

// the method contained at the delegate are wrapped in an object and

// passed.

this.begininvoke(new fhandler(facthandler), new object[]

{value, calculations});

}

protected void factorialminushandler(double value, double calculations)

{

this.begininvoke(new fhandler(fact1handler), new object []

{value, calculations});

}

protected void addtwohandler(int value, double calculations)

{

this.begininvoke(new a2handler(add2handler), new object[]

{value, calculations});

}

protected void loopdonehandler(double calculations, int count)

{

this.begininvoke(new ldhandler(ldonehandler), new object[]

{calculations, count});

}

看起来似乎事件处理程序仅仅是对下一个方法进行调用。实际上,该事件处理程序实现了在主操作线程上调用方法。这种方法可节省跨线程边界的调用,并使多线程应用程序能够有效运行而不必担心导致死锁。有关在多线程环境下使用控件的详细信息,请参见从线程操作控件。

保存您的工作。

从“调试”菜单中选择“启动”,测试该解决方案。

在文本框内键入 10000000 并单击“运行循环”。

此按钮下方的标签中显示“looping”。运行这个循环应该占用很长时间。如果它完成得太快,请相应地调整该数字的大小。

连续地快速单击仍在启用的三个按钮。您会发现所有按钮都响应您的输入。在“add two”下方的标签应该第一个显示结果。结果稍后将显示在阶乘按钮下方的标签中。估计这些结果会无限大,因为 10,000,000 的阶乘返回的数字对于双精度变量而言太大,以至超出了它包含的范围。最后,再过片刻,结果将返回到“运行循环”按钮下方。

正如刚刚观察到的,在四个单独的线程上同时执行四组独立的计算。用户界面保持对输入的响应,并在每个线程完成后返回结果。

协调线程

有经验的多线程应用程序用户可能会发现已键入的代码中存在细微缺陷。从 calculator.cs 中每个执行计算的子例程中撤回以下代码行:

vartotalcalculations += 1;

vartotalasofnow = vartotalcalculations;

这两行代码递增公共变量 vartotalcalculations 并将局部变量 vartotalasofnow 设为此值。然后,该值被返回给 frmcalculations,并显示在标签控件中。但返回的值正确吗?如果只有单个执行线程在运行,则答案明显是正确的。但是如果有多个线程在运行,答案则变得不太确定。每个线程都具有递增变量 vartotalcalculations 的能力。有可能出现这样的情况:在一个线程递增该变量之后,但在它将该值复制到 vartotalasofnow 之前,另一个线程可能通过递增该变量而更改它的值。这将导致有可能每个线程实际上在报告不正确的结果。visual c# 提供 lock 语句语句以允许线程的同步,从而确保每个线程始终返回准确的结果。lock 的语法如下所示:

lock(anobject)

{

// insert code that affects the object.

// insert more code that affects the object.

// insert more code that affects the object.

// release the lock.

}

输入 lock 块后,在指定的线程对所讨论的对象拥有专用锁之前,对指定表达式的执行一直被堵塞。在上面显示的示例中,对 anobject 的执行处于锁定状态。必须对返回引用的对象(而非返回值的对象)使用 lock。然后,执行以块的形式继续进行,而不会受到其他线程的干扰。作为一个单元执行的语句集称为“原子”。当遇到 } 时,表达式将被释放,线程可继续正常工作。

将 lock 语句添加到应用程序

在代码编辑器中打开 calculator.cs。

找到下列代码的每个实例:

vartotalcalculations += 1;

vartotalasofnow = vartotalcalculations;

应该有此代码的四个实例,每个计算方法中有一个。

修改此代码,使其显示为如下形式:

lock(this)

{

vartotalcalculations += 1;

vartotalasofnow = vartotalcalculations;

}

保存工作,并按上例所示进行测试。

您可能注意到对程序性能的细微影响。这是因为当组件获得排他锁后,线程的执行停止。尽管它保证了正确性,但这种方法抵消了多线程带来的某些性能优点。应该认真考虑锁定线程的必要性,并且仅当绝对必要时才予以实现。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 利用 Visual C# 创作简单的多线程组件(转载于MSDN)-.NET教程,C#语言
分享到: 更多 (0)

相关推荐

  • 暂无文章