开发者

make thread with method take sql connection

how to use ParameterizedThreadStart in c# I want to make threads take void开发者_Go百科 method and this method take sqlconnection ?


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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜