基本BackgroundWorker的用法与参数

编程入门 行业动态 更新时间:2024-10-28 09:23:10
本文介绍了基本BackgroundWorker的用法与参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的过程密集型的方法调用看起来是这样的:

My process intensive method call that I want to perform in a background thread looks like this:

object.Method(paramObj, paramObj2);

这三个对象都是那些我已经创建。现在,从我看到最初的例子,你可以传递一个对象到一个BackgroundWorker的DoWork的方法。但我应该如何去这样做,如果我需要通过额外的参数到该对象,就像我在这里干什么?我可以在一个单一的对象,把这个包,并用它做的,但我认为这将是明智的让别人对这个输入。

All three of these objects are ones I have created. Now, from the initial examples I have seen, you can pass an object into a backgroundworker's DoWork method. But how should I go about doing this if I need to pass additional parameters to that object, like I'm doing here? I could wrap this in a single object and be done with it, but I thought it would be smart to get someone else's input on this.

推荐答案

您可以将任何物体插入的RunWorkerAsync这个对象调用的参数,然后从DoWork的事件中获取的参数。您也可以从DoWork的事件使用的DoWorkEventArgs结果变量的RunWorkerCompleted事件传递参数。

You can pass any object into the object argument of the RunWorkerAsync call, and then retrieve the arguments from within the DoWork event. You can also pass arguments from the DoWork event to the RunWorkerCompleted event using the Result variable in the DoWorkEventArgs.

public Form1() { InitializeComponent(); BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); object paramObj = 1; object paramObj2 = 2; // The parameters you want to pass to the do work event of the background worker. object[] parameters = new object [] { paramObj, paramObj2 }; // This runs the event on new background worker thread. worker.RunWorkerAsync(parameters); } private void worker_DoWork(object sender, DoWorkEventArgs e) { object[] parameters = e.Argument as object[]; // do something. e.Result = true; } private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { object result = e.Result; // Handle what to do when complete. }

更多推荐

基本BackgroundWorker的用法与参数

本文发布于:2023-11-12 07:01:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580828.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   BackgroundWorker

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!