Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created October 4, 2019 15:55
Show Gist options
  • Select an option

  • Save unitycoder/f0eeb2e93882fea553941ce5e11daf26 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/f0eeb2e93882fea553941ce5e11daf26 to your computer and use it in GitHub Desktop.
C# Async Button Click Return Data
// button click
private async void OnGetUnityUpdatesClick(object sender, RoutedEventArgs e)
{
// if you call ShowTodaysInfo().Results, it blocks the call..
var task = ShowTodaysInfo();
var items = await task;
// items is your return value (string in this case, as the task below is Task<string>
}
// async stuff
private static async Task<string> ShowTodaysInfo()
{
string ret = $"Today is {DateTime.Today:D}\n" + "Today's hours of leisure: " + $"{await GetLeisureHours()}";
return ret;
}
static async Task<int> GetLeisureHours()
{
// Task.FromResult is a placeholder for actual work that returns a string.
var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());
Task.Delay(5000).Wait();
// The method then can process the result in some way.
int leisureHours;
if (today.First() == 'S')
leisureHours = 16;
else
leisureHours = 5;
return leisureHours;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment