I am using an insert statement as below, and I want to implement a basic 'multi thread' for it. I'm new to programming, could someone please explain how would I do that? I dont want to do it in just the display, but in the actual insert part.
I also wanna know is it possible to display the data in a normal listBox?
private void btnInsert_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection(c.getConnection()))
{
SqlCommand command = new
SqlCommand("INSERT INTO Weather_Details " +
"VALUES (@CityName, @CityDate, @MiniTemp, @MaxiTemp," +
" @Precipitation, @Humidity, @Windspeed)", connection);
//dont use ID field cos auto generated
command.Parameters.AddWithValue("@CityName", this.comboBox1.Text);
command.Parameters.AddWithValue("@CityDate", this.dateTimePicker1.Value);
command.Parameters.AddWithValue("@MiniTemp", this.numMini.Value);
command.Parameters.AddWithValue("@MaxiTemp", this.numMaxi.Value);
command.Parameters.AddWithValue("@Precipitation", this.numPrecip.Value);
command.Parameters.AddWithValue("@Humidity", this.numHumid.Value);
command.Parameters.AddWithValue("@Windspeed", this.numWind.Value);
connection.Open();
int temp = command.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("City has been captured successfully!",
"New City Added");
}
clear();
}
}
catch (SqlException ex)
{
//If displayed like this,
MessageBox.Show(ex.Message, "Error Message");
//instead of this,
//MessageBox.Show("Error Connecting to the Database", "Connection Error");
//it shows the actual error and not the hardcoded error of it not connecting to DB
}
}
}
It doesn't have to be complicated, I have this code but don't know how to implement it.
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Main Thread: {Thread.CurrentThread.ManagedThreadId} Started");
Task task1 = Task.Run(() =>
{
PrintCounter();
});
task1.Wait();
Console.WriteLine($"Main Thread: {Thread.CurrentThread.ManagedThreadId} Completed");
Console.ReadKey();
}
static void PrintCounter()
{
Console.WriteLine($"Cild Thread: {Thread.CurrentThread.ManagedThreadId} Started");
for (int count = 1; count <=5; count++)
{
Console.WriteLine($"Count: {count}");
}
Console.WriteLine($"Cild Thread: {Thread.CurrentThread.ManagedThreadId} Completed");
}
}
}