I try to write on database in multi-Thread at the same time
but the error occurred in myCommand.Connection.Open();
The error : Object reference not set to an instance of an object.
How can I Solve this problem ?
This example show the problem
private void button1_Click(object sender, EventArgs e)
{
new Thread(() =>
{
SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(1,'aaa')", Connection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}).Start();
new Thread(() =>
{
SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(2,'aaa')", Connection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}).Start();
new Thread(() =>
{
SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(3,'aaa')", Connection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}).Start();
new Thread(() =>
{
SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(4,'aaa')", Connection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}).Start();
}
You need a valid connection: