这是使用BackgroundWorker的正确方法吗? [英] Is this a correct way using BackgroundWorker?

查看:99
本文介绍了这是使用BackgroundWorker的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手.我想知道这是否是在单独的线程上快速运行函数的正确方法吗?有任何不良问题或可能的错误吗?谢谢

Hi, I am new to threading. I would like to know if this a correct way to quickly run a function on a separate thread? Any bad issue or possible errors? Thanks

public static void InvokeAsync<TParam, TResult>(Func<TParam, TResult> function, TParam parameter, Action<TResult> completedAction)
{
     BackgroundWorker bw = new BackgroundWorker();
     bw.DoWork += (sender, e) => e.Result = function(parameter);
     bw.RunWorkerCompleted += (sender, e) => completedAction((TResult)e.Result);
     bw.RunWorkerAsync();
}

推荐答案

我建​​议您阅读BackgroundWorker上的文章此处 [ ^ ].
I recommend you read the articles on BackgroundWorker here[^] and here[^].


易卜拉欣,您的示例代码是正确的-但与线程无关.

正如您所指出的,实际上,您正在做的是包装预订两个事件的工作,然后启动后台工作程序.所有这些都与您可能在后台线程(function的主体)上进行的操作以及它与调用线程上的内存的交互方式无关.

并且,您的测试证明InvokeAsync确实确实导致线程完成了分配的工作,然后报告其完成状态(或者,至少,我认为您的测试证明了这一点).

除了CIDev提供的链接之外,我还将阅读并了解以下内容:
*死锁(当两个或多个线程各自等待其他线程拥有的锁时发生),
*代码是线程安全的意味着什么以及什么做法以及
*可以使用哪些技术来确保您的代码是线程安全的.
Ibrahim, your sample code is correct - but strictly has nothing to do with threading.

As you pointed out, really what you''re doing is wrapping the work that subscribes to the two events, and then starts the background worker. And all of that has nothing to do with what you may be doing on the background thread (the body of function) and how it interacts with memory on the invoking thread.

And, your tests proved that InvokeAsync does indeed cause a thread to do the assigned work and then report its completion status (or, at least, I assume your tests demonstrate that).

As well as the links CIDev provided, I would read and understand about:
* deadlocks (which happen when two or more threads are each waiting on locks owned by the other threads),
* what it means for code to be thread-safe and what practices and
* what technologies are available to ensure that your code is thread-safe.


这篇关于这是使用BackgroundWorker的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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