New to c#. I have a winform with a combobox, button and progress bar. On the button click event text is taken from the textbox and used in a sql query. While this query is running, I would like a progress bar (marquee - does not need to show % complete) to animate, when the query is complete I would like it to stop.
I have tried the below code but get the error:

‘跨线程操作无效:控件’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强完全没有关系.已显示错误信息.它说您正在访问cbTest-ComboBox-在错误的线程上.您显然知道,您必须在UI线程上访问ProgressBar.为什么你认为ComboBox号可以做其他的事情呢?

解决方案将是根本不使用这种方法访问ComboBox.将该方法更改为也接受string,然后在创建Task之前从ComboBox中获取Text并传递string.

老实说,我只会在那个方法中进行查询.先做好查询前的所有UI操作,然后创建Task来执行query, passing in any data that is required. After the Task`完成,做查询后的UI操作.

Csharp相关问答推荐

在实际上是List T的 IESEARCH上多次调用First()是否不好?

等待限制选项似乎不适用于频道

什么是通过反射创建类的泛型接口方法的正确方法?

解析需要HttpClient和字符串的服务

从应用程序图API调用访问所有者字段

无法创建';';类型的';DbContext';.异常';无法解析类型';Microsoft.EntityFrameworkCore.DbContextOptions`1[Comm的服务

如何使用MoQ模拟Resources GroupCollection?

使用泛型可空类实现接口

在IAsyncEnumerable上先调用,然后跳过(1)可以吗?

net中从位图获取坐标和绘制折线

.NET 8 DI GetServices<;对象&>不工作

数据库.Migrate在对接容器重启时失败

在集成测试中可以在模拟InMemory数据库中设定数据种子

多个选项卡上的MudForm验证

为什么我的自定义Json.net转换器不工作?

如何在Cake脚本中设置MSBuild.exe的绝对路径

无效的Zip文件-Zip存档

如果所有";async任务方法()";调用都返回Task.FromResult()-是否同步执行?

C#中的逻辑运算符用作单词';is';and';and';

LINQ在GROUP BY和JOIN之后获取子列表