【发布时间】:2016-09-23 09:19:14
【问题描述】:
背景:我运行一个应用程序,其任务是在无限循环中打印“任务 + 编号”。我想知道当我关闭应用程序时任务发生了什么以及我如何看待它。
我的示例,我用它来查看运行任务:
//delegate to pring text in label
private delegate void SetTextToControlDelegate(string text, Control control);
private void SetTextToControl(string text, Control control)
{
if (control.InvokeRequired)
{
SetTextToControlDelegate deleg =
new SetTextToControlDelegate(SetTextToControl);
this.Invoke(deleg, new object[] { text, control });
}
else
{
control.Text = text;
}
}
//run a task
private void Run()
{
Task.Factory.StartNew(() =>
{
int i = 0;
while (true)
{
Thread.Sleep(1000);
i++;
string result = "task " + i.ToString();
SetTextToControl(result, label1);
}
});
}
//button to run task
private void button1_Click(object sender, EventArgs e)
{
try
{
Run();
}
catch (Exception ex)
{
SetTextToControl(ex.Message,label1);
}
}
【问题讨论】:
-
我认为如果你关闭整个应用程序,任务就会被杀死。
-
任务被杀死。线程属于进程。
标签: c# task backgroundworker