Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
error:

Managed Debugging Assistant 'ContextSwitchDeadlock' : 'The CLR has been unable to transition from COM context 0x11a4278 to COM context 0x11a41c0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.

What I have tried:

C#
private void btnbrowse_Click(object sender, EventArgs e)
{
	OpenFileDialog ofd = new OpenFileDialog();
	ofd.DefaultExt = ".csv";
	ofd.Filter = "Comma Separated (*.csv)|*.csv";
	ofd.ShowDialog();
	txtfilename.Text = ofd.FileName;

	DataTable dt = new DataTable();
	dataGridView1.DataSource = dt.DefaultView;
	{
	  
	}
}
	
private void btnclose_Click(object sender, EventArgs e)
{
	this.Close();
}

private void btnimport_Click(object sender, EventArgs e)
{
	Cursor = Cursors.WaitCursor;

	DataTable dt = GetDataFromFile();

	if (dt == null) return;

	SaveImportDataToDatabase(dt);

	MessageBox.Show("Data Import success!");
	txtfilename.Text = string.Empty;
	Cursor = Cursors.Default;

}

private DataTable GetDataFromFile()
{
	DataTable dt = new DataTable();

	try
	{
		using (StreamReader sr = new StreamReader(txtfilename.Text))
		{
			string header = sr.ReadLine();
			if (string.IsNullOrEmpty(header))
			{
				MessageBox.Show("no file data");
				return null;
			}
			string[] headerColumns = header.Split(',');
			foreach (string headerColumn in headerColumns)
			{
				dt.Columns.Add(headerColumn);
			}

			while (!sr.EndOfStream)
			{
				string line = sr.ReadLine();
				if (string.IsNullOrEmpty(line)) continue;
				string[] fields = line.Split(',');
				DataRow importedRow = dt.NewRow();

				for (int i = 0; i < fields.Count(); i++)
				{
					importedRow[i] = fields[i];
				}
				dt.Rows.Add(importedRow);
				
			}
		}
	}
	catch (Exception e)
	{
		Console.WriteLine("the file could not be read:");
		Console.WriteLine(e.Message);
	}

	return dt;
}
private void SaveImportDataToDatabase(DataTable S2P5)
{
	using (SqlConnection conn =New SqlConnection(@"Data Source=BL03\SQLEXPRESS; Initial Catalog=HDB; User Id=fit; Password=010"))
	{
		conn.Open();

		foreach (DataRow importRow in S2P5.Rows)
		{
			SqlCommand cmd = new SqlCommand ("INSERT INTO S2P5 (DateTime, Miliseconds, MachineAutoStartStop, Pressure)" + 
											 "VALUES (@DateTime, @Miliseconds, @MachineAutoStartStop, @Pressure)", conn);
		  
			cmd.Parameters.AddWithValue("@DateTime", (DateTime)importRow["DateTime"]);
			cmd.Parameters.AddWithValue("@Miliseconds", importRow["Miliseconds"]);
			cmd.Parameters.AddWithValue("@MachineAutoStartStop", importRow["MachineAutoStartStop"]);
			cmd.Parameters.AddWithValue("@Pressure", importRow["Pressure"]);

			cmd.ExecuteNonQuery();
		}
	}
}
Posted
Updated 29-Nov-22 13:51pm
v3
Comments
Graeme_Grant 29-Nov-22 2:31am    
You are doing all of your work on the main UI thread. Which line is throwing the error?
dhivyah jaiya 29-Nov-22 2:34am    
while data import into sql server this message will pop up.but the data can save in sql server.
Graeme_Grant 29-Nov-22 3:01am    
See OriginalGriff's answer. This is where I was heading. Part of understanding the solution is identifying where the issue is.
Richard Deeming 29-Nov-22 4:02am    
Firstly, applications should (almost) never connect to SQL Server using the sa account. That's an unlimited account which could be used to destroy your database, your server, or even your network. Instead, use a specific account with only the permissions required by your application.
Richard Deeming 29-Nov-22 4:03am    
Secondly, if that's your real sa password that you've just posted to a public forum, then change it immediately. And this time, pick a secure password, not something a hacker could guess in under a second!

1 solution

You are saving a large quantity of data to the database from a method called from a button event handler - which means it's all being executed on the main UI thread, and no UI events can be processed until the SaveImportDataToDatabase method is complete. Since that takes a seriously long time, the system is basically assuming your app is frozen.

Move that code into a BackgroundWorker and provide progress updates to your main thread and it should get rid of the error. It won't speed up the process though - you might want to look at using a DataAdapter to update the DB instead of individual INSERT operations - still in a background thread - but that would make progress reporting harder.
 
Share this answer
 
Comments
dhivyah jaiya 29-Nov-22 3:11am    
yes i am saving large quantity of data.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900