[英]Start second method after first method is finished with thread functionality c#
[英]Start same thread twice - the second time after the first one finished
因此,我制作了一个线程,该线程执行一个依赖于全局变量的函数。 之后,我想更改该变量并再次运行线程,以便它使用另一个参数再次执行我的过程。 问题是,我似乎无法弄清楚我的线程何时完成。 经过大量的搜寻后,我发现没有什么可以帮助我的。 这里有人可以帮忙吗? 提前致谢。 一些代码将不胜感激。 这是我的:
//temp_folder is global variable
temp_folder = APPDATA + "Local" + "\\" + "Temp\\";
Thread oThread = new Thread(new ThreadStart(clean_temp));
oThread.Start();
//Here I should wait for this oThread to finish, then change the temp_folder
//variable mentioned in comment down and start once again
//temp_folder = WINDIR + "\\" + "Temp\\";
//oThread.Start();
这是clean_temp()过程。 是的,这是GUI应用程序。
public void clean_temp()
{
DirectoryInfo directory = new DirectoryInfo(temp_folder);
try
{
DirectoryInfo[] folders = directory.GetDirectories();
foreach (DirectoryInfo folder in folders)
{
temp_folder = temp_folder + folder.Name + "\\";
clean_temp();
temp_folder = temp_folder.Replace(folder.Name + "\\", "");
}
}
catch { }
long sz;
double size, trenutna;
foreach (FileInfo file in directory.GetFiles())
{
sz = file.Length;
size = (double)sz / 1024.0;
trenutna = Convert.ToDouble(lbl_junk_size.Text);
trenutna += size;
MethodInvoker mi_invoker_size_change = new MethodInvoker(()=> lbl_junk_size.Text = trenutna.ToString());
lbl_junk_size.Invoke(mi_invoker_size_change);
MethodInvoker mi_invoker_count_change = new MethodInvoker(() => lbl_junk.Text = (Convert.ToInt64(lbl_junk.Text) + 1).ToString());
lbl_junk.Invoke(mi_invoker_count_change);
}
}
您可以使用Join()来确保线程已完成。
例如:
Thread oThread = new Thread(new ThreadStart(clean_temp));
oThread.Start();
oThread.Join();
我认为您在这里问错了问题。 而不是询问如何等待线程完成,您应该看看在第一个完成之后如何执行另一个操作。
在大多数情况下,您可以使用.Net中的Task API进行此操作。 任务为您提供了一种非常干净的方法来定义要异步执行的操作,然后在完成操作后执行其他操作。
因此,您可能可以执行以下伪代码:
var task = new Task(clean_temp);
task.ContinueWith(update_global_variable);
task.ContinueWith(clean_temp);
task.Wait();
实际的代码并非完全像这样,但是其想法是,您定义应完成的工作(调用clean_temp),然后在完成第一项工作后定义要完成的事情(update_global_variable),依此类推。 您可以链接任意数量的操作。
这可能比自己处理线程要干净得多。
编辑:实际上,您可以通过摆脱全局变量来进一步简化代码。
如果您修改clean_temp方法以采用一个输入参数来指定要清理的文件夹,那么您可以执行以下操作(再次,伪代码!!):
new Task(clean_temp, "C:\first temp folder")
.ContinueWith(clean_temp, "C:\second folder")
.Wait();
更清洁更安全:-)
如果使用的是C#5,请尝试将线程包装在任务中。 任务提供了一种名为“ ContinueWith”的方法,您可以在其中再次调用线程。 或使用“ await”进行异步调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.