Task return types gone wrong - “x has the wrong return type”

自古美人都是妖i 提交于 2019-12-12 01:36:51

问题


I have a line of code, that:

bool stop = await Task<bool>.Factory.StartNew(Listen, (TcpClient) client);

And the corresponding task:

public static async Task<bool> Listen(object state)
{
    TcpClient client = (TcpClient) state;
    NetworkStream connectionStream = client.GetStream();

    IPEndPoint endPoint = client.Client.RemoteEndPoint as IPEndPoint;

    byte[] buffer = new byte[4096];

    Encoding encoding = Encoding.UTF8;

    Random randomizer = null;

    // Are we still listening?
    bool listening = true;

    // Stop the server afterwards?
    bool stop = false;

    while (listening)
    {
        int bytesRead = await connectionStream.ReadAsync(buffer, 0, buffer.Length);

        if (bytesRead > 0)
        {
            // Create a new byte array for recieved data and populate
            // with data from buffer.
            byte[] messageBytes = new byte[bytesRead];
            Array.Copy(buffer, messageBytes, messageBytes.Length);

            // Generate a message from message bytes.
            string message = encoding.GetString(messageBytes);

            switch (message)
            {
                /*
                Message handling, where one can set stop to true.
                */
            }
        }

        if (bytesRead == 0 || listening == false)
        {   
            client.Client.Dispose();
            break;
        }
    }

    return stop;
}

I have left major parts out of the code, as I feel they do not affect the nature of question.

So yes, when running the application, I get an error:

76: <..>\Program.cs(63,63): Error CS0407: 'System.Threading.Tasks.Task<bool> SOQAsyncQuit.MainClass.Listen(object)' has the wrong return type (CS0407) (SOQAsyncQuit)

Well, I have tried to await Task.Factory.StartNew(...), but then I end up with a different error:

76: <..>\Program.cs(35,35): Error CS0121: The call is ambiguous between the following methods or properties: 'System.Threading.Tasks.TaskFactory.StartNew(System.Action<object>, object)' and 'System.Threading.Tasks.TaskFactory.StartNew<System.Threading.Tasks.Task<bool>>(System.Func<object,System.Threading.Tasks.Task<bool>>, object)' (CS0121) (SOQAsyncQuit)  
76: <..>\Program.cs(57,57): Error CS0407: 'System.Threading.Tasks.Task<bool> SOQAsyncQuit.MainClass.Listen(object)' has the wrong return type (CS0407) (SOQAsyncQuit)
76: <..>\Program.cs(29,29): Error CS0029: Cannot implicitly convert type 'void' to 'bool' (CS0029) (SOQAsyncQuit)

I have working void tasks, it's just this that I'm looking forward to transform into a typed result. Since I'm fairly new to C# and .NET in general, I'm out of clues here.

I have also been digging through: http://msdn.microsoft.com/en-us/library/hh524395.aspx, http://msdn.microsoft.com/en-us/library/dd537613(v=vs.110).aspx, some questions on SO, though, neither of them use the Task.Factory.StartNew and I cannot manage to link them together.

What's is the problem here?


回答1:


Usually with async it would be better to use Task.Run instead of StartNew. You can't if you plan on using a state object. In this case you need to "fix" the StartNew Usage to be:

bool stop = await Task<Task<bool>>.Factory.StartNew(Listen, client).Unwrap();

Listen's return value is of Task<bool> and not bool, and so StartNew's return type would need to be Task<Task<bool>> which you would need to await twice or use Unwrap. Task.Run was built with async in mind and so it does that all for you.



来源:https://stackoverflow.com/questions/23929158/task-return-types-gone-wrong-x-has-the-wrong-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!