我有一行代码,即:
bool stop = await Task<bool>.Factory.StartNew(Listen, (TcpClient) client);
以及相应的任务:
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;
}
我将主要部分排除在代码之外,因为我认为它们不会影响问题的性质。
所以是的,运行应用程序时,我收到错误:
76: <..>\Program.cs(63,63): Error CS0407: 'System.Threading.Tasks.Task<bool> SOQAsyncQuit.MainClass.Listen(object)' has the wrong return type (CS0407) (SOQAsyncQuit)
嗯,我已经尝试过await Task.Factory.StartNew(...)
,但后来我遇到了一个不同的错误:
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)
我有工作void
任务,这正是我期待将其转换为键入的结果。由于我对 C# 和 .NET 总体来说还很陌生,所以我在这里没有任何线索。
我也一直在挖掘:http://msdn.microsoft.com/en-us/library/hh524395.aspx http://msdn.microsoft.com/en-us/library/hh524395.aspx, http://msdn.microsoft.com/en-us/library/dd537613(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/dd537613%28v=vs.110%29.aspx,关于SO的一些问题,但是,他们都没有使用Task.Factory.StartNew
我无法将它们联系在一起。
这里有什么问题吗?