在新线程

时间:2017-02-02 17:53:27

标签: c#

我一直在尝试在新线程中创建函数调用,因为如果我使用我的主线程,那么我的应用程序太忙了,在函数运行时不能再使用了

现在我一直在尝试在新线程中创建函数调用:

private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(new ThreadStart(worker));
    thread.Start();
}

public void worker()
{
    using (var streamReader = File.OpenText(filePath))
    {
        var lines = streamReader.ReadToEnd().Split(new char[] { '\n' });
        var count = lines.Count();

        bunifuProgressBar1.MaximumValue = count;

        for (int i = 0; i < count; i++)
        {
            string[] words = lines[i].Split(':');
            string hash = mega.GenerateHash(words[0].ToLowerInvariant(), mega.PrepareKey(words[1].ToBytes()));

            bunifuCustomLabel4.Text = "Working: Total: " + count + ". Currently: " + (i + 1) + ".";
            bunifuCustomLabel4.Update();
            bunifuProgressBar1.Value = i + 1;
        }
    }
}

但现在我收到以下错误(使用谷歌翻译):

  

未处理的类型&#39; System.InvalidOperationException&#39;发生在System.Windows.Forms.dll

中      

附加信息:无效的线程跨越操作:对bunifuCustomLabel4控件的访问来自创建它的线程以外的线程。

我该如何解决此错误?我一直在谷歌搜索解决方案,但他们也没有工作。

我的最新尝试:

private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
    ThreadStart asyncCall = delegate
    {
        bunifuCustomLabel4.Invoke(new MethodInvoker(worker));
    };

    Thread thread = new Thread(new ThreadStart(worker));
    thread.Start();
}

1 个答案:

答案 0 :(得分:0)

您无法从后台线程更新UI。您必须使用int32[0...,0...]

从后台调用UI线程的更新

当您需要更新UI时,您可以执行与此类似的操作:

Control.Invoke()