【问题标题】:Calling a function from the main thread and making it work in parallel with a function in the main thread从主线程调用函数并使其与主线程中的函数并行工作
【发布时间】:2008-12-03 21:07:04
【问题描述】:

我真的很快就需要你的帮助来解决我的问题,而且它与上一期太接近了。 我想使用主线程中的线程调用一个函数。

更多解释,这里是我的代码示例: // 请看从 ( //-------- ) 开始的代码

    // this function is being called from the Form1 class Like this 
    //(this.Load += new System.EventHandler(this.Form1_Load);)

    private void Form1_Load(object sender, EventArgs e)
    {
        Common.MainForm = this;

        ftpServerIP = "74.220.215.77/ASGAQuraan";
        ftpUserID = "sanbouk@asgatech.com";
        ftpPassword = "asga_root";

        iStartConnection = true;
        iGetNarratorData = false;
        iGetNarratorsSuras = false;
        _isExpandedIndecies = new string[10];

        refreshPhons = true;
        count = 0;
        _btnDownload2PC.Enabled = false;
        _btnDownload2Phone.Enabled = false;

        //--------------------------------------------------------------------------------------
        //timer1.Tick() is a function which Gets Data rom Phone
        //Now, GetFromServer, and GetFromPC are 2 functions which i want to them 
        // to work in paralel with Timer1.Tick()
        //So, Fincally i want all 3 function work together with no gabs

         Timer1.Enabled = true;
        Timer1.Start();
        if (InvokeRequired)
        {
            Invoke(new GetFromServerHandler(GetFromServer));
        }
        else
        {
            ServerQuranTreeView.Nodes.Clear();
            GetFromServer();
            GetFromPC();
        }
    }

** 注意:在 GetFromServer 和 GetFromPC 中,我将在主线程中的树上更新 Form1(GUI),当我尝试使用线程(thread _t = new Thread(new ThreadStart(GetFromServer)))时出现此错误: " 正在从错误的线程调用对此控件执行的操作。使用 Control.Invoke 或 Control.BeginInvoke 编组到正确的线程以执行此操作。" **

我希望我能很好地解释我的问题。

提前致谢。

【问题讨论】:

  • 你敢于公开你的ftp地址、账号名和密码。我不会。
  • 你要么很勇敢,要么很愚蠢,要么是个蜜罐研究员。

标签: c#


【解决方案1】:

您不能从不同的线程对 UI 进行操作 - 但您可以让 GetFromServer 和 GetFromPC fetch 另一个线程上的数据,然后调用 Control.Invoke 以返回 UI线程来更新树视图。

请参阅my threading article,例如在另一个线程中执行后台工作然后编组返回。这篇文章是在 C#2 之前编写的,所以现在它稍微不那么笨重了。您还可以使用BackgroundWorker 来更轻松地报告进度等。

【讨论】:

    【解决方案2】:

    对于任何仅获取数据然后更新 GUI 并在下次有人调用它之前完成的操作, 使用 BackgroundWorker。

    它是一个为您简化线程编码的类。这样,您只需在一个函数中编写用于获取数据的代码,然后使用一种方法显示获取的数据。

    然后在要获取数据时调用它。

    BackgroundWorker 非常适用于任何 GUI 解决方案,您可以单击一个按钮在后台执行某些操作并随后更新某些内容。它还支持在获取数据时更新 GUI。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2022-10-15
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      相关资源
      最近更新 更多