Task - await - synchron - async

Noah Aas 380 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);
		}
	}
}
C#
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.
10,597 questions
0 comments No comments
{count} votes