Search code examples
c#taskbackgroundworker

What is happening with task if I close application C#


Background: I run an application with a task which prints 'task + number' in infinite loop. I want to know what is happeingn with the task when I close application and How I see it.

my example, which I use to see that run task:

//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);
    }
}

Solution

  • Your application is a process. Process is a parent of threads. Process also manages memory. So, threads (tasks) and their memory belongs to process. If the application (process) closes, it removes all its children. Tasks are killed, memory is freed.