markzzz
markzzz

Reputation: 47947

MethodInvoker lost?

This is my code:

private void TaskGestioneCartelle()
{
    Task.Factory.StartNew(() => GeneraListaCartelle())
        .ContinueWith(t => GeneraListaCartelleCompletata()
        , CancellationToken.None
        , TaskContinuationOptions.None
        , TaskScheduler.FromCurrentSynchronizationContext());
}

private void GeneraListaCartelle()
{
    // ... code
}

private void GeneraListaCartelleCompletata()
{
    Task.Factory.StartNew(() => CopiaCartelle())
        .ContinueWith(t => CopiaCartelleCompletato()
        , CancellationToken.None
        , TaskContinuationOptions.None
        , TaskScheduler.FromCurrentSynchronizationContext());
}

private void CopiaCartelle()
{
    if (txtLog.InvokeRequired)
    {
        txtLog.BeginInvoke(new MethodInvoker(delegate { txtLog.AppendText("Copio cartelle in corso..." + Environment.NewLine); }));
    }
}

It start a Thread. When finish, I start another thread (from the Continue with) and I try to write somethings in a Control on the UI. But in fact nothing is written on txtLog. Where am I wrong?

Upvotes: 0

Views: 97

Answers (1)

Habib
Habib

Reputation: 223187

I try to write somethings in a Control on the UI. But in fact nothing is written on txtLog. Where am I wrong?

Because at that time, Invoke is Not Required. You can modify your if statement and add an else part which would do the same.

private void CopiaCartelle()
{
    if (txtLog.InvokeRequired)
    {
        txtLog.BeginInvoke(new MethodInvoker(delegate { txtLog.AppendText("Copio cartelle in corso..." + Environment.NewLine); }));
    }
    else // this part when Invoke is not required. 
    {
     txtLog.AppendText("Copio cartelle in corso..." + Environment.NewLine);
    }
}

You can refactor the text append path to a method and call it that method from if-else

Upvotes: 3

Related Questions