如何将参数传递给新的backgroundworker [英] How to pass parameters to new backgroundworker

查看:75
本文介绍了如何将参数传递给新的backgroundworker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我想创建一个名为PlayerSearch的新后台工作者,为子SearchPlayers(Search As String)添加一个处理程序,然后运行BackgroundWorker的。然后它做PlayerSearch.RunWorkerAsync(Rixterz)。问题是你不能使用AddressOf的参数,所以我不能将SearchPlayers分配给PlayerSearch并使用搜索参数。有没有办法做到这一点?如果是这样,我怎么能把多个参数传递给它?



-Rixterz

Hello,

I'd like to create a new backgroundworker called PlayerSearch, add a handler to the sub SearchPlayers(Search As String), and then run the backgroundworker. Then it does PlayerSearch.RunWorkerAsync("Rixterz"). The problem is that you cannot use parameters with AddressOf, so I cannot assign SearchPlayers to PlayerSearch and use the "Search" parameter. Is there a way to do this? If so, how could I pass multiple parameters to it?

-Rixterz

推荐答案

你不要需要AddressOf,您需要做的就是在调用RunWorkerAsync方法时将对象作为参数传递。 DoWork事件处理程序有一个DoWorkEventArgs参数,该参数具有包含对象的Argument属性 - 您只需将其强制转换为您传递的类型(在本例中为字符串,但它可以是任何类型,包括列表你去了。
You don't need AddressOf, all you need to do is pass the object as the parameter when you call the RunWorkerAsync method. The DoWork event handler has a DoWorkEventArgs parameter, which has an Argument property which contains the object - all you have to do is cast it back to the type you passed through (in this case a string, but it can be any type including lists of your own classes) and off you go.


解决方案1中描述的方法并不是最好的,因为提到了这种可能容易出错的操作。更好的方法是使用实​​例(非静态)方法并将所有成员传递给this。请看我过去的答案:

如何将ref参数传递给线程 [ ^ ],

更改线程(生产者)启动后的参数 [ ^ ],

C#中的多线程 [ ^ ],

使代码线程安全 [ ^ ]。



-SA
The approach described in Solution 1 is not the best, because of that casting mentioned, a potentially error-prone operation. Much better approach is using an instance (non-static) method and passing all member through "this". Please see my past answers:
How to pass ref parameter to the thread[^],
Change parameters of thread (producer) after it is started[^],
MultiThreading in C#[^],
Making Code Thread Safe[^].

—SA


这篇关于如何将参数传递给新的backgroundworker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆