创建新线程,传递参数

发布于 2024-10-27 13:21:18 字数 621 浏览 1 评论 0原文

我想创建一个线程,然后将参数传递给它。但我不知道怎么办。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

枉心 2024-11-03 13:21:18

就我个人而言,我总是使用捕获的变量,即

int a = ...
string b = ...
ThreadStart work = delegate {
    var result = DoSomethingInteresting(a, b);
    // push result somewhere; might involve a UI
    // thread switch
};
new Thread(work).Start();

这意味着在构建过程中始终检查其正确性,这与传递对象参数不同。

Personally I always use captured variables, I.e.

int a = ...
string b = ...
ThreadStart work = delegate {
    var result = DoSomethingInteresting(a, b);
    // push result somewhere; might involve a UI
    // thread switch
};
new Thread(work).Start();

This means it is always checked for correctness during build, unlike passing an object parameter.

忘东忘西忘不掉你 2024-11-03 13:21:18

引用msdn

public class Work
{
    public static void Main()
    {
        // To start a thread using a shared thread procedure, use
        // the class name and method name when you create the 
        // ParameterizedThreadStart delegate. C# infers the 
        // appropriate delegate creation syntax:
        //    new ParameterizedThreadStart(Work.DoWork)
        //
        Thread newThread = new Thread(Work.DoWork);

        // Use the overload of the Start method that has a
        // parameter of type Object. You can create an object that
        // contains several pieces of data, or you can pass any 
        // reference type or value type. The following code passes
        // the integer value 42.
        //
        newThread.Start(42);

        // To start a thread using an instance method for the thread 
        // procedure, use the instance variable and method name when 
        // you create the ParameterizedThreadStart delegate. C# infers 
        // the appropriate delegate creation syntax:
        //    new ParameterizedThreadStart(w.DoMoreWork)
        //
        Work w = new Work();
        newThread = new Thread(w.DoMoreWork);

        // Pass an object containing data for the thread.
        //
        newThread.Start("The answer.");
    }

    public static void DoWork(object data)
    {
        Console.WriteLine("Static thread procedure. Data='{0}'",
            data);
    }

    public void DoMoreWork(object data)
    {
        Console.WriteLine("Instance thread procedure. Data='{0}'",
            data);
    }
}

这样你就可以看到你创建了以 object 作为参数的方法,并将该参数传递给 Thread 类的 Start 方法

Citing the msdn:

public class Work
{
    public static void Main()
    {
        // To start a thread using a shared thread procedure, use
        // the class name and method name when you create the 
        // ParameterizedThreadStart delegate. C# infers the 
        // appropriate delegate creation syntax:
        //    new ParameterizedThreadStart(Work.DoWork)
        //
        Thread newThread = new Thread(Work.DoWork);

        // Use the overload of the Start method that has a
        // parameter of type Object. You can create an object that
        // contains several pieces of data, or you can pass any 
        // reference type or value type. The following code passes
        // the integer value 42.
        //
        newThread.Start(42);

        // To start a thread using an instance method for the thread 
        // procedure, use the instance variable and method name when 
        // you create the ParameterizedThreadStart delegate. C# infers 
        // the appropriate delegate creation syntax:
        //    new ParameterizedThreadStart(w.DoMoreWork)
        //
        Work w = new Work();
        newThread = new Thread(w.DoMoreWork);

        // Pass an object containing data for the thread.
        //
        newThread.Start("The answer.");
    }

    public static void DoWork(object data)
    {
        Console.WriteLine("Static thread procedure. Data='{0}'",
            data);
    }

    public void DoMoreWork(object data)
    {
        Console.WriteLine("Instance thread procedure. Data='{0}'",
            data);
    }
}

so as you can see you create a method with an object as a parameter and pass this parameter to the Start method of the Thread class

回梦 2024-11-03 13:21:18

拉法尔的解决方案会起作用,但我不确定你如何从中获得返回值。正如 Martinho 指出的,ParameterizedThreadStart 要求该方法返回 void。尝试使用BackgroundWorker 来代替。

像这样称呼它。

var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync(url);

这是 DoWork,基本上是 GetHTML 的修改版本。

static void bw_DoWork(object sender, DoWorkEventArgs e)
{
    WebClient webClient = new WebClient();
    string siteURL = (string)e.Argument;

    try
    {
        string sitePrefix = siteURL.Substring(0, 7);
        if(sitePrefix != "http://")
            siteURL = "http://" + siteURL;
    }
    catch
    {
        siteURL = "http://" + siteURL;
    }

    try
    {
        e.Result = webClient.DownloadString(siteURL);
    }
    catch
    {
        e.Result = "404";
    }
}

最后,在 bw_RunWorkerCompleted 中执行类似的操作

static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    string result;
    result = (string)e.Result;
    //do something with result
}

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.

var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync(url);

Here is DoWork, basically a modified version of GetHTML.

static void bw_DoWork(object sender, DoWorkEventArgs e)
{
    WebClient webClient = new WebClient();
    string siteURL = (string)e.Argument;

    try
    {
        string sitePrefix = siteURL.Substring(0, 7);
        if(sitePrefix != "http://")
            siteURL = "http://" + siteURL;
    }
    catch
    {
        siteURL = "http://" + siteURL;
    }

    try
    {
        e.Result = webClient.DownloadString(siteURL);
    }
    catch
    {
        e.Result = "404";
    }
}

Finally, do something like this in bw_RunWorkerCompleted

static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    string result;
    result = (string)e.Result;
    //do something with result
}
执笏见 2024-11-03 13:21:18

您是否查看了 ParametrizedThreadStart 的文档?您需要一个接受对象参数并且不返回任何内容的方法。因此,您需要相应地更改方法签名:

static void GetHTML(object data)
{
    string siteUrl = (string) data; // cast argument to string
    // blah blah
}

然后您需要找出使用返回值的方法。

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:

static void GetHTML(object data)
{
    string siteUrl = (string) data; // cast argument to string
    // blah blah
}

And then you need to figure out a way of using the return value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文