2013-02-16 19 views
6

Durante la compilazione il mio programma (compilo da MonoDevelop IDE) ricevo un errore:La chiamata è ambigua tra le seguenti metodi o proprietà С #

Error CS0121: The call is ambiguous between the following methods or properties: System.Threading.Thread.Thread(System.Threading.ThreadStart)' and System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)' (CS0121)

Qui la parte di codice.

Thread thread = new Thread(delegate { 
    try 
    { 
     Helper.CopyFolder(from, to); 
     Helper.RunProgram("chown", "-R www-data:www-data " + to); 
    } 
    catch (Exception exception) 
    { 
     Helper.DeactivateThread(Thread.CurrentThread.Name); 
    } 
    Helper.DeactivateThread(Thread.CurrentThread.Name); 
}); 
thread.IsBackground = true; 
thread.Priority = ThreadPriority.Lowest; 
thread.Name = name; 
thread.Start(); 

Grazie per l'attenzione

risposta

8

delegate { ... } è un un metodo anonimo che può essere assegnato a qualsiasi tipo delegato, tra cui ThreadStart e ParameterizedThreadStart. Poiché la classe Thread fornisce sovraccarichi del costruttore con entrambi i tipi di argomento, è ambiguo il significato di sovraccarico del costruttore.

delegate() { ... } (nota la parentesi) è un metodo anonimo che non accetta argomenti. Può essere assegnato a solo per delegare tipi che non accettano argomenti, come Action o ThreadStart.

Quindi, modificare il codice per

Thread thread = new Thread(delegate() { 

se si desidera utilizzare l'overload del costruttore ThreadStart, o per

Thread thread = new Thread(delegate(object state) { 

se si desidera utilizzare l'overload ParameterizedThreadStart costruttore.

2

Questo errore viene generato quando si dispone di un metodo che ha sovraccarichi e l'uso potrebbero lavorare con entrambi sovraccarico. Il compilatore non è sicuro del sovraccarico che si desidera chiamare, quindi è necessario indicarlo esplicitamente mediante il cast del parametro. Un modo per farlo è come questo:

Thread thread = new Thread((ThreadStart)delegate { 
    try 
    { 
     Helper.CopyFolder(from, to); 
     Helper.RunProgram("chown", "-R www-data:www-data " + to); 
    } 
    catch (Exception exception) 
    { 
     Helper.DeactivateThread(Thread.CurrentThread.Name); 
    } 
    Helper.DeactivateThread(Thread.CurrentThread.Name); 
}); 
0

In alternativa, è possibile utilizzare un lambda:

Thread thread = new Thread(() => 
{ 
    try 
    { 
     Helper.CopyFolder(from, to); 
     Helper.RunProgram("chown", "-R www-data:www-data " + to); 
    } 
    catch (Exception exception) 
    { 
     Helper.DeactivateThread(Thread.CurrentThread.Name); 
    } 
    Helper.DeactivateThread(Thread.CurrentThread.Name); 
}); 

thread.IsBackground = true; 
thread.Priority = ThreadPriority.Lowest; 
thread.Name = name; 
thread.Start();   
Problemi correlati