views:

65

answers:

3

how to use ParameterizedThreadStart in c# I want to make threads take void method and this method take sqlconnection ?

+3  A: 

First off, that's probably not the best idea. Don't be passing around SqlConnection objects between threads. There's no telling what kind of horrible bugs will be introduced that way.

Second, you pass your parameters to the Start() method. Instead of passing a SqlConnection, I suggest passing the connection string instead and constructing a SqlConnection per thread.

Dave Markle
yes I will make the connection before I started threads and pass the sqlconnection for each thread this is the code I want to call ParameterizedThreadStart.that take this method public void geturls(SqlConnection con,string keyword) { List<List<string>> Urls = new List<List<string>>(); List<string> UrlsResult = new List<string>(); Urls = rankerurl.Extract(con, keyword); rankerurl.Set_Use_Rating(con, Urls); rankerurl.Merge_Rating(con, Urls); UrlsResult = Save_Urls_InFile(Urls, keyword, con); }
salamonti
Again, not a good idea. Make each connection inside each thread. This is not going to cost you any performance because .NET does connection pooling behind the scenes for you.
Dave Markle
+1  A: 

The ParameterizedThreadStart delegate only takes an Object parameter, so the method has to match that. You have to cast the Object reference to SqlConnection in the method:

public void Work(Object o) {
  SqlConnection conn = o as SqlConnection;
  ...
}

When calling it you don't have to specifically cast the SqlConnection to Object, that is done implicitly:

Thread t = new Thread(Work);
t.Start(conn);

However, you might want to consider that the method should create it's own connection. The connection object is not thread safe, so you can't use the same connetion object in more than one thread at a time.

Guffa
A: 

Here's a C# 3.0 approach

using (SqlConnection connection = new SqlConnection("mydb"))
{
    Thread thread = new Thread(delegate()
    {
        connection.Open();
    });
    thread.Start();
}

As mentioned, passing a SqlConnection into a thread isn't the best solution. Creating it inside the thread method would be a wiser choice, and passing the connection string instead (or making the connection string a static member of a class).

Chris S