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

问题描述

如何通过在C#中的参数 Thread.ThreadStart()的方法?

假设我有办法叫下载

 公共无效下载(字符串文件名)
{
    //下载code
}
 

在main方法现在,我已经创建了一个线程:

 线程的线程=新主题(新的ThreadStart(下载(文件名));
 

我如何可以传递参数给的ThreadStart ,目标方法的参数?

解决方案

最简单的就是

 字符串文件名= ...
线程线程=新主题(()=>下载(文件名));
thread.Start();
 

的优势(S)这个(超过 ParameterizedThreadStart )是可以传递多个参数,你会得到编译时检查,而不需要投从对象所有的时间。

How to pass parameters to Thread.ThreadStart() method in C#?

Suppose I have method called download

public void download(string filename)
{
    //download code
}

Now i have created one thread in main method :

Thread thread = new Thread(new ThreadStart(download(filename));

How can I pass parameters to ThreadStart with target method with parameters?

解决方案

The simplest is just

string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();

The advantage(s) of this (over ParameterizedThreadStart) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object all the time.

这篇关于如何传递参数的ThreadStart方法主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 11:00