创建新线程,传递参数

Sta*_*tan 11 c# multithreading

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

Thread siteDownloader = new Thread(new ParameterizedThreadStart(GetHTML));
Run Code Online (Sandbox Code Playgroud)

这是我想作为新线程启动的功能.

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 21

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

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();
Run Code Online (Sandbox Code Playgroud)

这意味着在构建期间始终检查它是否正确,这与传递对象参数不同.


Raf*_*jer 12

引用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以看到使用objectas作为参数创建方法,并将此参数传递给类的Start方法Thread

  • 即使你刚从msdn复制它.好例子. (4认同)