TcpClient.ConnectAsync Methode async / await / Task

Markus Freitag 3,791 Reputation points
2023-02-09T18:55:17.6+00:00

How can I call an async function from a standard function?

What do I have to do? What is the syntax?

The await does that.

The function waits for feedback, but is processed asynchronously.

A UserInterface does not hang then, is further operable?

With or without 'await' nothing goes. Why?

public static int Main(String[] args)
{
	// here is not async
	Test();
	return 0;
}


public static async Task Test()
{
// here is async
	using (TcpClient tcp = new TcpClient())
	{
		IAsyncResult ar = tcp.BeginConnect("127.0.0.1", 6000, null, null);
		System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
		try
		{
			if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(15), true))
			{
				tcp.Close();
				throw new TimeoutException();
			}

			tcp.EndConnect(ar);
		}
		finally
		{
			wh.Close();

enter image description here

async

Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Michael Taylor 61,111 Reputation points
    2023-02-09T23:07:03.2833333+00:00

    What version of C# are you using? In later versions (7.1+) of C# Main can be async so you can await inside Main just like you would anywhere else.

    public static async Task<int> Main(String[] args)
    {
       await Test();
       return 0;
    }
    

    For other synchronous methods then you can use a hack.

    void SomeSyncMethod ()
    {
       //Block until done
       Test().GetAwaiter().GetResult();
       //Alternative version but it doesn't propagate exceptions the same
       //Test().Wait();
    }
    

    But this is generally not recommended as it can cause issues depending upon how this method is being called. So use it only when you absolutely must.


1 additional answer

Sort by: Most helpful
  1. Jack J Jun 25,316 Reputation points
    2023-02-14T07:56:23.2133333+00:00

    @Michael Taylor , Welcome to Microsoft Q&A, you could try the following code to call an async function from a standard function.

    In console app, you could call it in main method like the following:

     static async Task Main(string[] args)
            {
                await Test();
            }
    
    

    In winform app, you could call it in button_click event like the following:

     private async void button2_Click(object sender, EventArgs e)
            {
                await Test();
            }
    
    

    Hope my code could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.