Author : HASSAN MD TAREQ

Conforming to async method during development

Trick 1

public async Task<T> FetchAsync()
{
	return await Task.Run(new Func<T>(() => {

		T t = new T();
		
		// modify t
		
		// ... ... ...

		return t;
	}));
}

Example

public async Task<List<FooModel>> FetchFoosAsync()
{
	return await Task.Run(new Func<List<FooModel>>(() => {

		var types = new List<FooModel>()
		{
			new FooModel() { Id = "1" , Name = "Foo 1" },
			new FooModel() { Id = "2" , Name = "Foo 2" }
		};

		return types;
	}));
}

Trick 2

await Task.Yield();

// do the rest here
// ... ... ...

Examples

// Example 1 - Blazor component
<ChildComponent OnClickCallback="@(async () => { await Task.Yield(); messageText = "Blaze It!"; })" />


// Example 2
private async void button_Click(object sender, EventArgs e)
{
  await Task.Yield(); // Make us async right away

  var data = ExecuteFooOnUIThread(); // This will run on the UI thread at some point later

  await UseDataAsync(data);
}


// Example 3
private static void Main()
{
	RecursiveMethod().Wait();
}

private static async Task RecursiveMethod()
{
	await Task.Delay(1);
	//await Task.Yield(); // Uncomment this line to prevent stackoverlfow.
	await RecursiveMethod();
}

More: