Uczyń event dla przycisku asynchronicznie wykonywanym. Najprościej możesz w taki sposób:
private async Task button1_Click(object sender, EventArgs e)
{
this.button1.Text = "Trwa generowanie";
var mysqlManager = new mysqlManager();
await Task.Run(() =>
{
mysqlManager.saveManager(this.textBox1.Text); // raczej ta linijka wykonuje się dość długo ;p
});
}
Najlepiej będzie oczywiście uczynić tylko tę logikę asynchroniczną, która tego naprawdę potrzebuje – chociażby użyć metod SqlConnection.OpenAsync, SqlCommand.ExecuteReaderAsync czy SqlDataReader.ReadAsync:
public abstract class mysqlManager
{
public async Task saveManager(string date)
{
string csv = "header;header2\r\n";
string sql = "SELECT * FROM ...";
StringBuilder errorMessages = new StringBuilder();
string connectionString = "Data Source=";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
try
{
command.CommandTimeout = 300;
await command.Connection.OpenAsync();
SqlDataReader dataReader;
dataReader = await command.ExecuteReaderAsync();
while (await dataReader.ReadAsync())
{
for (int i = 0; i < 20; i++)
{
string source = i != 18 ? dataReader.GetValue(i).ToString() : "";
csv += Regex.Replace(source.Replace("\r", " ").Replace("\n", " ").Replace("\r\n", " ").Replace("\t", " "), @"[ ]{2,}", " ");
csv += i < 19 ? ";" : "\r\n";
}
}
command.Connection.Close();
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
Console.ReadKey();
}
}
}
}
BTW, możesz uprościć tworzenie ścieżki zapisu pliku:
string filePath = Path.Combine(Directory.GetCurrentDirectory(), date + "_generated.csv");
EDIT: usunięcie zbędnych linijek w drugim wycinku kodu.