我真的很快就需要你的帮助来解决我的问题,而且它与上一期太接近了。 我想使用主线程中的线程调用一个函数。
更多解释,这里是我的代码示例: //请查看从 (//-------- ) 开始的代码
// 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/