后台工作者
我制定了一种列出路径中所有 ftp 文件夹的方法。
我的问题是我需要将其作为数组返回。
但它是一个后台工作者,我只能将它返回到“RunWorkerCompleted”,
与 e.Result。
1)如何将参数传递给方法?(后台工作人员的)
2) 如何将文件夹数组返回到正常方法?
就像这样:
private void btnOpen_Click_1(object sender, EventArgs e)
{
string[]/List... a= getDirectories(**path**)?
}
I have made a method that lists all of the ftp folders in a path.
My problem is that I need to return this as an array.
But it is a background worker, and I can only return it to the "RunWorkerCompleted",
with e.Result.
1) How can I pass a parameter to the method?(of the background-worker)
2) How can I return the array of folders to a normal method?
Like so:
private void btnOpen_Click_1(object sender, EventArgs e)
{
string[]/List... a= getDirectories(**path**)?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将列表作为表单本身的成员,并让工作人员在其工作时添加到其中(因为工作人员代码属于表单,因此该成员将在范围内)。
因此,如果您希望工作人员将其项目添加到列表的特定实例中;只需在触发工作人员之前先将其设置到成员中即可。
但是,您必须小心使用这种方法,不要在工作线程运行时访问该列表;因为它不是线程安全的。在 .Net 4 中,您可以使用 ConcurrentBag - 它是线程安全的。
如果您不想这样做,那么正如您所说,在
RunWorkerCompleted
事件中传递的事件参数的Result
成员将用于传达结果 - 并且是您返回列表的地方。您还可以使用ProgressChanged
事件 (在 MSDN 上)也可以流回结果的单个快照。我不认为这是不合理的:异步操作与同步调用是根本不同的范例,您根本无法使用相同的调用和返回语义。
You can have a List as a member of the form itself, and have the worker add into that as it does it's work (since the worker code will belong to the form, the member will be in scope).
Therefore if you want the worker to add its items into a specific instance of a list; just set that into the member first before triggering the worker.
However you must be careful with this approach not to access that list whilst the worker is running; as it's not thread safe. In .Net 4 you could use the ConcurrentBag - which is thread-safe.
If you don't want to do that, then the
Result
member of the event arguments passed in theRunWorkerCompleted
event is, as you say, used to communicate results - and that is where you would return your list. You can also use theProgressChanged
event (on MSDN) to stream back individual snapshot of results as well.I don't think this is unreasonable: async operations are a fundamentally different paradigm to synchronous calls, you simply can't use the same call-and-return semantics.
您可以传递您的参数,因为它们是对象。 BackgroundWorker 采用
object
参数。object
的变量可以携带任何内容:数组、引用和变量。示例:
在方法中:
当工作完成时:
You can pass your arguments as they are objects. BackgroundWorker takes a parameter of
object
. A variable ofobject
can carry anything: array, references and variables.Example:
in the method:
When the work has completed: