Tag: async await

如何生成任务以解包

有人可以解释这两个陈述之间的区别: Task bTask = backup.BackupCurrentDatabaseAsync() .ContinueWith(_ => CompressArchiveAsync()); //unwrap the tasks to produce one entire task Task t = bTask.Unwrap(); VS Task bTask = backup.BackupCurrentDatabaseAsync() .ContinueWith(_ => { CompressArchiveAsync(); }); //unwrap the tasks to produce one entire task Task t = bTask.Unwrap(); ExtractArchiveAsync() , BackupCurrentDatabaseAsync() , RestoreDatabaseAsync()都返回一个Task 。 这里,第一个Continuation返回一个Task 。 然后我可以Unwrap()这个任务,将Continuations放在结果(内部)任务上。 第二个版本不编译。 这里唯一不同的是CompressArchiveAsync()周围的大括号。 我试图访问结果(内部) Task以检查Task.Status […]

。继续在任务完成之前开始

我在C#,VS2012,WPF 4.5中有以下代码。 我的期望是, .ContinueWith将在任务完成后执行(这是一个延续的完整目的,不是吗?)。 这应该在finalResult中产生值2。 int myTestInt = 0; Task task = Task.Factory.StartNew(async () => { myTestInt = 1; await Task.Delay(TimeSpan.FromSeconds(6)); myTestInt = 2; }).ContinueWith(_ => { int finalResult = myTestInt; }); 实际上, finalResult被赋值为1。 所以似乎已经在await语句上启动了continuation。 这是预期的行为吗? 我在这里错过了什么吗? 任务完成后我不能依赖ContinueWith启动吗? 更新: 贾斯汀的回答激发了我检查以下内容: int myTestInt = 0; Task task=Task.Factory.StartNew(async () => { myTestInt = 1; await Task.Delay(TimeSpan.FromSeconds(6)); myTestInt […]

为什么IQueryables没有SingleOrDefaultAsync?

以下代码无法编译,因为SingleOrDefaultAsync()不是GetAppointments()的合适扩展。 我只是想知道为什么…… public IQueryable GetAppointments() { return Context.Appointments; } public async Task GetAppointmentAsync(int appointmentId) { return await GetAppointments().SingleOrDefaultAsync(a => a.ID == appointmentId); } 我使用的是EF 6.0.0。 请忽略我在这里做的事情。 我只是想让事情变得比他们在我的项目中更容易。

如果有条件,是否可以使用Task ?

在Windows Phone 8中,我有方法public async Task authentication() 。 该函数的返回类型是bool但是当我尝试在if条件中使用其返回值时,错误表示无法将Task转换为bool 。 public async Task authentication() { var pairs = new List<KeyValuePair> { new KeyValuePair (“user”, _username), new KeyValuePair (“password”, _password) }; var serverData = serverConnection.connect(“login.php”, pairs); RootObject json = JsonConvert.DeserializeObject(await serverData); if (json.logined != “false”) { _firsname = json.data.firsname; _lastname = json.data.lastname; _id = json.data.id; _phone = […]

调用API时在何处使用并发

在ac #project项目中我正在调用一个web api,问题是我在一个方法的循环中做它们。 通常没有那么多,但即使我正在考虑利用并行性。 到目前为止我正在尝试的是 public void DeployView(int itemId, string itemCode, int environmentTypeId) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(ConfigurationManager.AppSettings[“ApiUrl”]); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); var agents = _agentRepository.GetAgentsByitemId(itemId); var tasks = agents.Select(async a => { var viewPostRequest = new { AgentId = a.AgentId, itemCode = itemCode, EnvironmentId = environmentTypeId }; var […]

检查对异步方法的Received()调用

当我运行以下代码时: [Test] public async Task Can_Test_Update() { var response = await _controller.UpdateAsync(Guid.NewGuid()); response.Valid.Should().BeTrue(); _commands.Received().UpdateAsync( Arg.Is( l => l.Status == Status.Updated)); } 如果我在“ _commands.Received().UpdateAsync ”之前添加“ await ”,它会抛出一个空引用exception。 我该如何阻止这种情况发生,或await没有必要?

C#Mysql – 在async await服务器上使用数据库查询的锁

我有TcpListener类,我正在使用async/await读写。 对于这个服务器,我创建了单个数据库实例,我准备了所有数据库查询。 但对于一个以上的TcpClient我一直在exception: MySql.Data.MySqlClient.MySqlException发生MySql.Data.dll类型的exception,但未在用户代码中处理 附加信息:已经有一个与此Connection关联的打开DataReader ,必须先关闭它。 如果我理解正确,那么一次数据库查询就不会超过一个async客户端的问题。 所以我只是在我的查询中添加了锁,这样一切似乎都很好。 // One MySqlConnection instance for whole program. lock (thisLock) { var cmd = connection.CreateCommand(); cmd.CommandText = “SELECT Count(*) FROM logins WHERE username = @user AND password = @pass”; cmd.Parameters.AddWithValue(“@user”, username); cmd.Parameters.AddWithValue(“@pass”, password); var count = int.Parse(cmd.ExecuteScalar().ToString()); return count > 0; } 我也尝试使用这个方法为每个查询创建新连接,如SO社区的某个人所提到的,但这个方法比锁慢得多: using (MySqlConnection connection = new […]

同步执行异步function

我已就此主题进行了大量搜索,并且我在此网站上阅读了有关此主题的大部分post,但我仍然感到困惑,我需要一个直接的答案。 这是我的情况: 我有一个已建立的Winform应用程序,我无法将其全部“异步”。 我现在被迫使用一个全部写为异步函数的外部库。 在我的申请中,我有 /// /// This function I can’t change it to an ‘async’ /// public void MySyncFunction() { //This function is my point in my application where I have to call the //other ‘async’ functions but I can’t change the function itself to ‘async’ try { //I need to call the MyAsyncDriverFunction() […]

我可以使用System.Linq.Expressions动态生成异步方法吗?

我知道编译器无法将异步lambda表达式转换为表达式树,但是可以手动生成表达式树吗? var expr = Expression.Lambda<Func>( // how do I use ‘await’ in the body here? ); var func = expr.Compile(); 我在Expression类中找不到与async或await相关的任何方法,但也许还有另一种方法?

我可以为此方案设计任何无锁解决方案

我有一个简单的Employee类如下 public class Employee { public int ID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } } 然后我有一个ProcessEmployees类,它在名为ProcessThisEmployee的方法中对这些员工进行并发处理。 在这种方法中,我必须调用第三方库方法。 到目前为止一切都很简单。 问题是用户在进行操作时选择取消此操作的某个时候,我需要对尚未完成处理的任何ThirdPartyLibrary类实例进行一些清理。 注意我对ThirdPartyLibrary类没有任何控制,并且它没有任何取消现有任务的机制。 它提供了一个Clean方法,我可以在任何调用SomeAPI尚未完成的实例上调用它。 因此,我正在维护所有实例的本地列表。 当用户选择取消操作时,我调用我的类的CleaupIfUserCancelOperation方法,即清理我本地列表中第三方库实例的方法。 以下是我的代码。 class ProcessEmployees { private List _Employees; List libraries = new List(); private object sync = new object(); public ProcessEmployees() […]