Skip to content

Instantly share code, notes, and snippets.

@dougvdotcom

dougvdotcom/await-async.cs

Last active Nov 13, 2015
Embed
What would you like to do?
Demonstration of await and async keywords in c#
using System;
using System.Threading.Tasks;
using LinqToTwitter;
using System.Data.SqlClient;
namespace linq2twitter_demo {
public class BaseballGame {
public int Id { get; set; }
public DateTime GameDate { get; set; }
public string HomeTeamName { get; set; }
public int HomeTeamScore { get; set; }
public string AwayTeamName { get; set; }
public int AwayTeamScore { get; set; }
}
class Program {
static void Main() {
Console.WriteLine("Program started.");
var t = Task.Run(() => { BoxScore() });
t.WaitAll();
Console.WriteLine("Program complete.");
Console.Read();
}
public async void BoxScore() {
var game = new BaseballGame {
Id = 100001,
GameDate = new DateTime(2015, 9, 1),
HomeTeamName = "Astros",
HomeTeamScore = 7,
AwayTeamName = "Yankees",
AwayTeamScore = 3
};
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = "your consumer KEY from part 1",
ConsumerSecret = "your consumer SECRET from part 1",
AccessToken = "your access TOKEN from part 1",
AccessTokenSecret = "your ACCESS SECRET from part 1"
}
};
var context = new TwitterContext(auth);
Task<Status> sendTweetTask = context.TweetAsync($"FINAL: {game.HomeTeamName} {game.HomeTeamScore}, {game.AwayTeamName} {game.AwayTeamScore}");
using(var conn = new SqlConnection("some-connection-string")) {
using(var cmd = new SqlCommand($"INSERT INTO ScoresTable (Id, GameDate, HomeTeamName, HomeTeamScore, AwayTeamName, AwayTeamScore) VALUES ({game.Id}, {game.GameDate}, '{game.HomeTeamName}', {game.HomeTeamScore}, '{game.AwayTeamName}', {game.AwayTeamScore}", conn) {
conn.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Game result saved to database.");
}
}
var tweetStatus = await sendTweetTask;
if(tweetStatus != null) {
Console.WriteLine($"Tweet sent. Id: {tweetStatus.StatusID}");
}
else {
Console.WriteLine("Tweet was not sent.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment