MethodInvoker输了?

时间:2013-04-18 10:19:44

标签: c# multithreading

这是我的代码:

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

它启动一个线程。完成后,我启动另一个线程(来自Continue with),我尝试在UI上的Control中编写一些东西。但实际上没有任何内容写在txtLog上。我哪里错了?

1 个答案:

答案 0 :(得分:3)

  

我尝试在UI上的Control中编写一些东西。但事实上没什么   写在txtLog上。我哪里错了?

因为在那时,Invoke不是必需的。您可以修改if语句并添加else部分,这样做也是如此。

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

您可以重构方法的文本追加路径,并从if-else

中调用该方法
相关问题