c# - 从主线程调用函数并使其与主线程中的函数并行工作

标签 c#

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

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

    // 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 编码到正确的线程以执行此操作。”**

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

提前致谢。

最佳答案

您不能从不同的线程对 UI 执行操作 - 但您可以让 GetFromServer 和 GetFromPC 获取另一个线程上的数据,然后调用 Control.Invoke 返回到 UI线程更新 TreeView 。

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

关于c# - 从主线程调用函数并使其与主线程中的函数并行工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/336831/

相关文章:

c# - Selenium C# 中的 headless (headless) Firefox

c# - 如何允许匿名用户访问 MVC 中的某个给定页面?

c# - 从接口(interface)继承的类中的列表 - 从类中添加到列表?

c# - MVC 字符串值保存 Javascript 代码,但 Js 无法识别引号

c# - 为什么长时间运行不返回任何数据的 SQL 命令会产生数百 MB 的网络流量

c# - DataContractSerializer 和反序列化 Web 服务响应类型

c# - 使用搜索栏在 map 上过滤图钉及其值

c# - 如何调试我的 TFS 事件?

c# - 像在十六进制编辑器中一样将字节数据转换为字符串输出

c# - Calendar.GetDayOfWeek() 可以返回 (DayOfWeek)7 吗?