以文本方式查看主题 - 中文XML论坛 - 专业的XML技术讨论区 (http://bbs.xml.org.cn/index.asp) -- 『 Dot NET,C#,ASP,VB 』 (http://bbs.xml.org.cn/list.asp?boardid=43) ---- c# Passing Parameters to Threads (http://bbs.xml.org.cn/dispbbs.asp?boardid=43&rootid=&id=76429) |
-- 作者:卷积内核 -- 发布时间:8/19/2009 11:58:00 AM -- c# Passing Parameters to Threads Often when you start a thread, you want to give it some parameters - usually some data it has to process, a queue to wait on, etc. The ThreadStart delegate doesn't take any parameters, so the information has to be stored somewhere else if you are going to create a new thread yourself. Typically, this means creating a new instance of a class, and using that instance to store the information. Often the class itself can contain the delegate used for starting the thread. For example, we might have a program which needs to fetch the contents of various URLs, and wants to do it in the background. You could write code like this: public class UrlFetcher public UrlFetcher (string url) public void Fetch() [... in a different class ...]
In some cases, you actually just wish to call a method in some class (possibly the currently executing class) with a specific parameter. In that case, you may wish to use a nested class whose purpose is just to make this call - the state is stored in the class, and the delegate used to start the thread just calls the "real" method with the appropriate parameter. (Note that the object on which to call the method in the first place will also be required as state unless the method is static.) Using the thread pool instead .NET 2.0 solution 1: anonymous methods (with and without the thread pool) ThreadStart starter = delegate { Fetch (myUrl); };
(This could have all been expressed within a single step, creating both the thread and the delegate in the same line of code, but I believe the above is more readable.) Here's similar code to use a WaitCallback and queue the job in ThreadPool: WaitCallback callback = delegate (object state) { Fetch ((string)state); };
Note the way that the state is declared. .NET 2.0 solution 2: ParameterizedThreadStart [In some method or other] [And the actual method...] |
W 3 C h i n a ( since 2003 ) 旗 下 站 点 苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》 |
4,793.945ms |