Вопрос

While compiling my program (I compile it from MonoDevelop IDE) I receive an error:

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)

Here the part of code.

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();
Это было полезно?

Решение

delegate { ... } is a an anonymous method that can be assigned to any delegate type, including ThreadStart and ParameterizedThreadStart. Since the Thread Class provides constructor overloads with both argument types, it's ambiguous which constructor overload is meant.

delegate() { ... } (note the parenthesis) is a an anonymous method that takes no arguments. It can be assigned only to delegate types that take no arguments, such as Action or ThreadStart.

So, change your code to

Thread thread = new Thread(delegate() {

if you want to use the ThreadStart constructor overload, or to

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

if you want to use the ParameterizedThreadStart constructor overload.

Другие советы

This error is thrown when you have a method that has overloads and your usage could work with either overload. The compiler isn't sure which overload you want to call so you need to explicitly state it by casting the parameter. One way to do this is like this:

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

Alternatively, you can use a 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();        
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top