Task - await - synchron - async

Noah Aas 985 Reputation points
2024-07-11T18:10:59.4966667+00:00

Hello! My goal is to send a request and receive an answer. I have a C# WinForm application.

The button is synchronous Task<(bool, string, int)> task = Task.Run<(bool, string, int)>

I can write it that way for the call, that is usual and correct, which would be my question, among others. If I have to do something in parallel, the task is a good way, better than thread.

private void btnTest_Click(object sender, EventArgs e)
{
	// Usage example:
	string template = File.ReadAllText("..\\..\\template.xml");
	string filledTemplate = ScadaClient.ReplacePlaceholder(template, "$$$MyValue$$$", "ActualValue");
	
	//Task<(bool, string, int)> task = Task.Run<(bool, string, int)>(async () => await ScadaClient.PostXmlToScadaAsync("http://example.com/api", filledTemplate, "your_auth_token"));
	Task<(bool, string, int)> task = Task.Run<(bool, string, int)>(async () => await ScadaClient.PostXmlToScadaAsync("https://48ba6c60-1fcc-48d6-81be-b2a3ac734d79.mock.pstmn.io/PostTestRequest", filledTemplate, "your_auth_token"));


	(bool responseState, string responseData, int statusCode) = task.Result;    

	if (responseState)
	{
		// Process successful response
		if (statusCode == 200)
		{
			Trace.WriteLine("Success: " + responseData);
		}
		else
		{
			Trace.WriteLine("Unexpected success status code: " + statusCode);
		}
	}
	else
	{
		// Handle error
		if (statusCode == 400)
		{
			Trace.WriteLine("Bad Request: " + responseData);
		}
		else if (statusCode == 500)
		{
			Trace.WriteLine("Internal Server Error: " + responseData);
		}
		else
		{
			Trace.WriteLine("Unhandled error status code: " + statusCode);
		}
	}
}
Developer technologies C#
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-07-11T20:33:27.28+00:00

    the task.Result stall the main thread until complete. you should use fire and forget.

    private void btnTest_Click(object sender, EventArgs e)
    {
    	// Usage example:
    	string template = File.ReadAllText("..\\..\\template.xml");
    	string filledTemplate = ScadaClient.ReplacePlaceholder(template, "$$$MyValue$$$", "ActualValue");
    
        Task.Run(async () => 
        {
            // call service
            var (bool responseState, string responseData, int statusCode) = await ScadaClient.PostXmlToScadaAsync("https://48ba6c60-1fcc-48d6-81be-b2a3ac734d79.mock.pstmn.io/PostTestRequest", filledTemplate, "your_auth_token"));
    
        	if (responseState)
    	    {
    		    // Process successful response
    		    if (statusCode == 200)
    			{
    				Trace.WriteLine("Success: " + responseData);
    			}
    			else
    			{
    				Trace.WriteLine("Unexpected success status code: " + statusCode);
    			}
    		}
    		else
    		{
    			// Handle error
    			if (statusCode == 400)
    			{
    				Trace.WriteLine("Bad Request: " + responseData);
    			}
    			else if (statusCode == 500)
    			{
    				Trace.WriteLine("Internal Server Error: " + responseData);
    			}
    			else
    			{
    				Trace.WriteLine("Unhandled error status code: " + statusCode);
    			}
    		}
    	});
    }
    

    note: because you are in a thread, the code inside the Task.Run can not update the UI, unless it marshals to the main thread via the controls .Invoke() method. see docs.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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