刚刚得到VS2012,并试图获得async处理。 比方说,我有一个方法,从阻塞源获取一些值。 我不希望方法的调用者阻止。 我可以编写方法来获取一个callback,当值到达时被调用,但是由于我使用的是C#5,我决定使方法asynchronous,因此调用者不必处理callback: // contrived example (edited in response to Servy's comment) public static Task<string> PromptForStringAsync(string prompt) { return Task.Factory.StartNew(() => { Console.Write(prompt); return Console.ReadLine(); }); } 这是一个调用它的示例方法。 如果PromptForStringAsync不是asynchronous,则此方法需要在callback中嵌套callback。 通过asynchronous,我可以用这种非常自然的方式来编写我的方法: public static async Task GetNameAsync() { string firstname = await PromptForStringAsync("Enter your first name: "); Console.WriteLine("Welcome {0}.", firstname); string lastname = await PromptForStringAsync("Enter your […]
这不是“如何在不等待的情况下安全地调用C#中的asynchronous方法”的复制。 我如何很好地抑制以下警告? 警告CS4014:由于此呼叫未等待,所以在呼叫完成之前继续执行当前方法。 考虑将“await”运算符应用于调用的结果。 一个简单的例子: static async Task WorkAsync() { await Task.Delay(1000); Console.WriteLine("Done!"); } static async Task StartWorkAsync() { WorkAsync(); // I want fire-and-forget // more unrelated async/await stuff here, eg: // … await Task.Delay(2000); } 我尝试过但不喜欢的东西: static async Task StartWorkAsync() { #pragma warning disable 4014 WorkAsync(); // I want fire-and-forget here #pragma warning restore […]
在metro应用程序中,我需要执行一些WCF调用。 有大量的电话要做,所以我需要做一个并行循环。 问题是并行循环在WCF调用全部完成之前退出。 你将如何重构这个按预期工作? var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; var customers = new System.Collections.Concurrent.BlockingCollection<Customer>(); Parallel.ForEach(ids, async i => { ICustomerRepo repo = new CustomerRepo(); var cust = await repo.GetCustomer(i); customers.Add(cust); }); foreach ( var customer in customers ) { Console.WriteLine(customer.ID); } Console.ReadKey();
我在创build的Web API中执行以下操作: // GET api/<controller> [HttpGet] [Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")] public CartTotalsDTO GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri] bool refresh = false) { return delegateHelper.GetProductsWithHistory(CustomerContext.Current.GetContactById(pharmacyId), refresh); } 对这个web服务的调用是通过一个jQuery的Ajax调用完成的: $.ajax({ url: "/api/products/pharmacies/<%# Farmacia.PrimaryKeyId.Value.ToString() %>/page/" + vm.currentPage() + "/" + filter, type: "GET", dataType: "json", success: function (result) { vm.items([]); var data = result.Products; vm.totalUnits(result.TotalUnits); } }); […]
我有3个任务: private async Task<Cat> FeedCat() {} private async Task<House> SellHouse() {} private async Task<Tesla> BuyCar() {} 他们都需要运行之前我的代码可以继续,我也需要结果。 没有一个结果有任何共同之处 我如何打电话,等待3个任务完成,然后得到结果?
我刚刚看到了三个关于TPL使用的例程,它们做的是同样的工作 这里是代码 public static void Main() { Thread.CurrentThread.Name = "Main"; // Create a task and supply a user delegate by using a lambda expression. Task taskA = new Task( () => Console.WriteLine("Hello from taskA.")); // Start the task. taskA.Start(); // Output a message from the calling thread. Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name); taskA.Wait(); } public […]
我正在尝试将async / await集成到我们的服务总线中。 我基于此示例实现了SingleThreadSynchronizationContext http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx 。 它的工作正常,除了一件事: TransactionScope 。 我等待TransactionScope内部的东西,它打破了TransactionScope 。 TransactionScope似乎并不async / await ,当然是因为它使用ThreadStaticAttribute将事物存储在线程中。 我得到这个例外: “TransactionScope嵌套错误。” 我尝试在排队任务之前保存TransactionScope数据,并在运行之前将其还原,但似乎没有改变任何事情。 而TransactionScope代码是一团糟,所以真的很难理解那里发生的事情。 有没有办法让它工作? 是否有一些替代TransactionScope ?
我最近正在阅读一些使用大量asynchronous方法的代码,但有时候需要同步执行它们。 代码确实: Foo foo = GetFooAsync(…).GetAwaiter().GetResult(); 这是一样的 Foo foo = GetFooAsync(…).Result; ?
我有这个简单的代码: public static async Task<int> SumTwoOperationsAsync() { var firstTask = GetOperationOneAsync(); var secondTask = GetOperationTwoAsync(); return await firstTask + await secondTask; } private async Task<int> GetOperationOneAsync() { await Task.Delay(500); // Just to simulate an operation taking time return 10; } private async Task<int> GetOperationTwoAsync() { await Task.Delay(100); // Just to simulate an operation taking time […]
我使用asynchronous/等待和Task很多,但从来没有使用Task.Yield() ,说实话,即使所有的解释,我不明白为什么我会需要这种方法。 有人可以给出一个很好的例子, Yield()是必需的吗?