2013-04-18 29 views
0

這是我的代碼:MethodInvoker輸了?

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),並嘗試在UI上的Control中編寫一些東西。但實際上txtLog沒有寫任何內容。我錯在哪裏?

回答

3

我嘗試在用戶界面的控件上編寫一些東西。但實際上沒有什麼 寫在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

+0

這個方法我想刪除'TaskScheduler.FromCurrentSynchronizationContext());'(用於實驗的緣故),將使當前的代碼工作, 對? –

+0

@ByteBlast,可能是,不確定,但OP可以試試 – Habib

+0

那麼什麼時候需要InvokeRequired?我在一個線程,它應該是必需的:O – markzzz