C# 新手。我有一个带有组合框、按钮和进度栏的 winform。在按钮单击事件上,从文本框中获取文本并在 SQL 查询中使用。当这个查询运行时,我想要一个进度条(选取框 - 不需要显示完成百分比)来动画,当查询完成时我希望它停止。我已尝试以下代码,但收到错误“跨线程操作无效:从创建它的线程以外的线程访问控制'cbTest'。”。
private System.Windows.Forms.ProgressBar _progressBar;
public Test()
{
InitializeComponent();
_progressBar = progressBar;
}
private void Form1_Load_1(object sender, EventArgs e)
{
_progressBar.Style = ProgressBarStyle.Marquee;
_progressBar.MarqueeAnimationSpeed = 0;
}
public async void btn_Click(object sender, EventArgs e)
{
await Task.Run(() => GetValues(_progressBar));
}
private void GetValues(System.Windows.Forms.ProgressBar progressBar)
{
progressBar.Invoke(new System.Action(() =>
{
progressBar.MarqueeAnimationSpeed = 30;
}));
Sql.SqlQuery("exec Test..sp_Test " + cbTest.Text);
progressBar.Invoke(new System.Action(() =>
{
progressBar.Style = ProgressBarStyle.Blocks;
progressBar.Style = ProgressBarStyle.Marquee;
progressBar.MarqueeAnimationSpeed = 0;
}));
}
public static void SqlQuery(string queryString, string connectionString = "Data Source= Test; Initial Catalog = Test; Integrated Security = True")
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.CommandTimeout = 300;
command.Connection.Open();
command.ExecuteNonQuery();
}
}
这与
ProgressBar
的关系绝对为零。 Raed 错误消息。它表示您正在错误的线程上访问 cbTest
- ComboBox
。您显然知道您必须访问 UI 线程上的 ProgressBar
。为什么您认为对 ComboBox
采取其他措施是可以的?
解决方案是根本不访问该方法中的
ComboBox
。更改该方法以接受 string
,然后在创建 Text
之前从 ComboBox
获取 Task
并将该 string
传入。
老实说,除了该方法中的查询之外,我什么也不做。首先执行所有预查询 UI 操作,然后创建
Task
来执行查询, passing in any data that is required. After the
Task` 完成,执行查询后 UI 操作。