创建新线程,传递参数
我想创建一个线程,然后将参数传递给它。但我不知道怎么办。
Thread siteDownloader = new Thread(new ParameterizedThreadStart(GetHTML));
这是我想作为新线程启动的函数。
static string GetHTML(string siteURL)
{
WebClient webClient = new WebClient();
try
{
string sitePrefix = siteURL.Substring(0, 7);
if (sitePrefix != "http://")
{
siteURL = "http://" + siteURL;
}
}
catch
{
siteURL = "http://" + siteURL;
}
try
{
return webClient.DownloadString(siteURL);
}
catch
{
return "404";
}
}
I want to create a thread and then pass parameters to it. But I don't know how.
Thread siteDownloader = new Thread(new ParameterizedThreadStart(GetHTML));
This is function that I want to launch as new thread.
static string GetHTML(string siteURL)
{
WebClient webClient = new WebClient();
try
{
string sitePrefix = siteURL.Substring(0, 7);
if (sitePrefix != "http://")
{
siteURL = "http://" + siteURL;
}
}
catch
{
siteURL = "http://" + siteURL;
}
try
{
return webClient.DownloadString(siteURL);
}
catch
{
return "404";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
就我个人而言,我总是使用捕获的变量,即
这意味着在构建过程中始终检查其正确性,这与传递对象参数不同。
Personally I always use captured variables, I.e.
This means it is always checked for correctness during build, unlike passing an object parameter.
引用msdn:
这样你就可以看到你创建了以
object
作为参数的方法,并将该参数传递给Thread
类的Start
方法Citing the msdn:
so as you can see you create a method with an
object
as a parameter and pass this parameter to theStart
method of theThread
class拉法尔的解决方案会起作用,但我不确定你如何从中获得返回值。正如 Martinho 指出的,ParameterizedThreadStart 要求该方法返回 void。尝试使用BackgroundWorker 来代替。
像这样称呼它。
这是 DoWork,基本上是 GetHTML 的修改版本。
最后,在 bw_RunWorkerCompleted 中执行类似的操作
Rafal's solution will work, but I'm not sure how you get your return value from that. As Martinho points out, ParameterizedThreadStart requires a void return on the method. Try using a BackgroundWorker instead.
Call it like this.
Here is DoWork, basically a modified version of GetHTML.
Finally, do something like this in bw_RunWorkerCompleted
您是否查看了
ParametrizedThreadStart
的文档?您需要一个接受对象参数并且不返回任何内容的方法。因此,您需要相应地更改方法签名:然后您需要找出使用返回值的方法。
Did you look at the docs for
ParametrizedThreadStart
? You need a method that takes an object parameter and returns nothing. So, you'll need to change your method signature accordingly:And then you need to figure out a way of using the return value.