C# EF的异步

注:此demo程序是从microsoft的ef文章中拿过来的,仅用于记录,以后自己使用时方便查询,相关网址如下:

https://docs.microsoft.com/zh-cn/ef/ef6/get-started

此文记录c# ef框架下的异步操作写法,实际上,根据代码来看,应该和是否ef无关,由于不太熟悉ef和c#之间的关系,所以就按照下载文档时的文章标题来描述此段文字了。

这里简单记录两个demo程序,一个是同步的,一个是异步的,做个简单的对比就知道之间的差别了。

同步demo如下:

using System;
using System.Linq;
namespace AsyncDemo
{
	class Program
	{
		static void Main(string[] args)
		{
			PerformDatabaseOperations();
			Console.WriteLine("Quote of the day");
			Console.WriteLine(" Don't worry about the world coming to an end today... ");
			Console.WriteLine(" It's already tomorrow in Australia.");
			Console.WriteLine();
			Console.WriteLine("Press any key to exit...");
			Console.ReadKey();
		}

		public static void PerformDatabaseOperations()
		{
			using (var db = new BloggingContext())
			{
				// Create a new blog and save it
				db.Blogs.Add(new Blog
				{
					Name = "Test Blog #" + (db.Blogs.Count() + 1)
				});
				Console.WriteLine("Calling SaveChanges.");
				db.SaveChanges();
				Console.WriteLine("SaveChanges completed.");
				// Query for all blogs ordered by name
				Console.WriteLine("Executing query.");
				var blogs = (from b in db.Blogs	orderby b.Name select b).ToList();
				// Write all blogs out to Console
				Console.WriteLine("Query completed with following results:");
				foreach (var blog in blogs)
				{
					Console.WriteLine(" " + blog.Name);
				}
			}
		}
	}
}

异步demo如下:

using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace AsyncDemo
{
	class Program
	{
		static void Main(string[] args)
		{
			var task = PerformDatabaseOperations();
			Console.WriteLine("Quote of the day");
			Console.WriteLine(" Don't worry about the world coming to an end today... ");
			Console.WriteLine(" It's already tomorrow in Australia.");
			task.Wait();
			Console.WriteLine();
			Console.WriteLine("Press any key to exit...");
			Console.ReadKey();
		}

		public static async Task PerformDatabaseOperations()
		{
			using (var db = new BloggingContext())
			{
				// Create a new blog and save it
				db.Blogs.Add(new Blog
				{
					Name = "Test Blog #" + (db.Blogs.Count() + 1)
				});
				Console.WriteLine("Calling SaveChanges.");
				await db.SaveChangesAsync();
				Console.WriteLine("SaveChanges completed.");
				// Query for all blogs ordered by name
				Console.WriteLine("Executing query.");
				var blogs = await (from b in db.Blogs orderby b.Name select b).ToListAsync();
				// Write all blogs out to Console
				Console.WriteLine("Query completed with following results:");
				foreach (var blog in blogs)
				{
					Console.WriteLine(" - " + blog.Name);
				}
			}
		}
	}
}

两个程序的差别不大,主要是把函数定义成“任务”,需要异步的部分,就调用异步接口。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值