Hello everyone.
I would like to ask a question about Access 2016.
I am using Access 2016 from an application created in C# using an OLEDB provider.
When I create a connection instance for every access, the application crashes. The frequency is about once every half day.
The code is as follows
private void button1_Click(object sender, EventArgs e)
{
Task.Run(async () =>
{
var i = 0;
while (true)
{
using var connection = new OleDbConnection(_connectionString);
await connection.OpenAsync();
using var commend = new OleDbCommand(_query, connection);
_ = await commend.ExecuteNonQueryAsync();
Invoke((MethodInvoker)(() => textBox1.Text = (++i).ToString()));
await Task.Delay(100);
}
});
}
I have also found that this problem can be remedied by making sure to reuse the connection.
private void button2_Click(object sender, EventArgs e)
{
Task.Run(async () =>
{
var i = 0;
while (true)
{
if (_connection == default(OleDbConnection))
{
_connection ?? = new OleDbConnection(_connectionString2);
await _connection.OpenAsync();
}
using var commend = new OleDbCommand(_query, _connection);
_ = await commend.ExecuteNonQueryAsync();
Invoke((MethodInvoker)(() => textBox1.Text = (++i).ToString()));
await Task.Delay(100);
}
});
}
I would like to know for the sake of later learning, is the above usage not recommended in Access 2016?
Thank you very much.
Added on 2021-02-17
I'm sorry that there was a problem with my code.
I tried modifying it to use the Using block, but that didn't solve the problem and caused the crash.
private void button1_Click(object sender, EventArgs e)
{
Task.Run(async () =>
{
var i = 0;
while (true)
{
using (var connection = new OleDbConnection(_connectionString))
{
await connection.OpenAsync();
using (var commend = new OleDbCommand(_query, connection))
{
_ = await commend.ExecuteNonQueryAsync();
Invoke((MethodInvoker)(() => textBox1.Text = (++i).ToString()));
}
}
await Task.Delay(100);
}
});
}
Added on 2021-02-18
Added a try catch clause to check for exceptions. However, I could not catch the exception and it crashed.
[HandleProcessCorruptedStateExceptions()]
private void button1_Click(object sender, EventArgs e)
{
Task.Run(async () =>
{
var i = 0;
while (true)
{
try
{
using (var connection = new OleDbConnection(_connectionString))
{
await connection.OpenAsync();
using (var commend = new OleDbCommand(_query, connection))
{
_ = await commend.ExecuteNonQueryAsync();
Invoke((MethodInvoker)(() => textBox1.Text = (++i).ToString()));
}
}
}
catch
{
Debug.WriteLine("error");
}
await Task.Delay(100);
}
});
}