none
can you give an example of the scenario that a void method can be used as Func<Task>?! RRS feed

  • Question

  • void Method1(){...}

    Task.Run(Method1); //Error

    Error description: Severity Code Description Project File Line Suppression State Error CS0121 The call is ambiguous between the following methods or properties: 'Task.Run(Action)' and 'Task.Run(Func<Task>)' 

    ok if the call is ambiguous between 'Task.Run(Action)' and 'Task.Run(Func<Task>)' what is a possible scenario that "Method1" can be used as a Func<Task>?

    Thanks :)


    Sunday, January 6, 2019 2:11 PM

Answers

All replies

  • Currently your method is returning void not Task so you can change it to return Task instead of void. For instance let's say we return an int value :

    public static Task Method1()
    {
        return Task.FromResult<int>(1);
    }


    and now we can write like following to call it:

    Task.Run((Func<Task>)Method1);

    even the following works without casting it to Func<Task>  when i test this in VS 2017:

    Task.Run(Method1);


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites


    Sunday, January 6, 2019 3:36 PM
  • I wanted a void method to run in a new thread. the method doesn't need a return type (I mean I can force it to have one but it will be useless). I wanted to use Task.Run() to achieve my goal that I faced this weird error saying: ambiguous between 'Task.Run(Action)' and 'Task.Run(Func<Task>)' 

    so I was curious if that is even possible that a void method is able to be used as a Func<Task>! if it's not possible how exactly it is ambiguous?!

    I already know that the solution is to explicitly tell the compiler that I want the method as Action, but my question is that why I can't do it implicitly?

    BTW, this problem doesn't exist when I use:

    void Method1(){...} var task= new Task(Method1); //No Error

    task.Start();






    Sunday, January 6, 2019 3:53 PM
  • To avoid this contestable ambiguity, try selecting the “C# 7.3” version in Build, Advanced window of Project Properties, if available [https://github.com/dotnet/roslyn/issues/26077].

    Sunday, January 6, 2019 4:14 PM