There are various problems with this code. First, using async void is only meant for event handlers. An async void method can't be awaited and any exceptions it throws can't be handled. Second, Task.Factory.StartNew(()=>client.Connect(host,port)) fakes asynchronous execution. It still blocks a thread. Asynchronous execution means that no thread is blocked while waiting for the operation to complete.
I assume you use TcpClient. This class already has a ConnectAsync method that connects in an asynchronous manner. You could simplify your code to this:
private async Task StartClient()
{
try
{
await client.ConnectAsync(host,port);
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
If you want to start the client in response to a UI event, eg a button click, you'd write :
async void Button1_Click(object sender, EventArgs e)
{
await StartClient();
}
or
async void Button1_Click(object sender, EventArgs e)
{
try
{
await StartClient();
//Work with the client
}
catch(Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
Finally, use a logging library instead of MessageBox.Show, eg log4net so you don't lose exception messages due to threading issues.
awaitwill wrap all exception in AggregateException - you should catch for that first and then checkaggregateException.InnerExceptionscollection for actual exception which caused errorasync void. It can't be awaited and any exceptions it raises can't be handled. It's only meant for event handlersTask.Factory.StartNewlike this? Why notTask.Run? Even better, why don't you use the asynchronous version of Connect? TcpClient.ConnectAsync for example is a truly asynchronous method whileTask.Run(()=>client.Connect())just fakes itTask.Resultthrows anAggregateException,awaitthrows the exception that occured