MethodInvoker lost?

本文关键字:lost MethodInvoker | 更新日期: 2023-09-27 18:09:54

这是我的代码:

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上的控件中写一些东西。但实际上txtLog上什么也没写。我哪里错了?

MethodInvoker lost?

我试着在UI上的控件中写一些东西。但实际上什么都没有是写在txtLog上的。我哪里错了?

因为此时不需要调用。您可以修改您的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

调用该方法