Tag: async await

异步/等待具有进度/取消的长时间运行的API方法

编辑我认为强制等待异步调用worker的正确方法是使用Task.Run,​​如下所示: await Task.Run(() => builder.Build(dlg.FileName, cts.Token, new Progress(ReportProgress))); 从http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx获得了一些亮点。 这应该很容易,但我是async / await的新手,所以请耐心等待。 我正在构建一个类库,使用一些长时间运行的操作来公开API。 在过去,我使用BackgroundWorker来处理进度报告和取消,就像在这个简化的代码片段中一样: public void DoSomething(object sender, DoWorkEventArgs e) { BackgroundWorker bw = (BackgroundWorker)sender; // e.Argument is any object as passed by consumer via RunWorkerAsync… do { // … do something … // abort if requested if (bw.CancellationPending) { e.Cancel = true; break; } […]

如何更快地运行此entity framework示例

我有这个代码用于向数据库添加大约1500条记录: async void button7_Click(object sender, EventArgs e) { var task = await Task.Run(() => { Random rnd = new Random(); for (int i = 0; i <= 1500; i++) { db.Tbls.Add(new Tbl() { Name = "User" + i + 1, Num = rnd.Next(10, i + 10) / 10 }); progress.Report(i * 100 / 1500); } […]

之前是否发现了在C#中使用async / await?

在关于async / await的stackoverflow之前的一个问题之后,在我看来,await比营销建议更强大和更通用。 它似乎是构建计算表达式的一般方法,就像在F#中一样。 因此,经过一番努力,我想出了一些成功执行的代码,如下所示。 using FluentAssertions; using System.Collections.Generic; namespace EnumerableViaAwait.Specs { [global::Microsoft.VisualStudio.TestTools.UnitTesting.TestClass] public class MyTestClass { public IEnumerable Numbers() { return EnumeratorMonad.Build(async Yield => { await Yield(11); await Yield(22); await Yield(33); }); } [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod] public void TestEnum() { var v = Numbers(); var e = v.GetEnumerator(); int[] expected = { 11, 22, 33 }; […]

如何使用reflection调用通用异步方法

public interface IBar { } public class Bar : IBar { } public class Bar2 : IBar { } public interface IFoo { Task Get(T o) where T : IBar; } public class Foo : IFoo { public async Task Get(T o) where T : IBar { … } } 然后我可以使用reflection调用此方法: var method = typeof(IFoo).GetMethod(nameof(IFoo.Get)); […]

异步任务中的HttpContext.Current null

我有一个使用存储库( userRepo )的方法: public override Task CreateLocalUserAsync(IUser user, string password, CancellationToken cancellationToken) { var task = new Task(() => { TUserEntity newUser = new TUserEntity { Id = user.Id, UserName = user.UserName, Password = password }; userRepo.Save(newUser).Flush(); return new IdentityResult(true); }, cancellationToken); task.Start(); return task; } userRepo对象具有使用HttpContext.Current的依赖项。 使用ninject InRequestScope解决了这两个问题。 在Mvc 5中的默认AccountController中调用上面的方法: var result = await […]

async / await with ConfigureAwait的continueOnCapturedContext参数和SynchronizationContext用于异步延续

我想先把代码放一下,然后解释一下情况并根据这个问题提出我的问题: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private async void Button_Click_2(object sender, RoutedEventArgs e) { var result = await GetValuesAsync(); Foo.Text += result; } public async Task GetValuesAsync() { using (var httpClient = new HttpClient()) { var response = await httpClient .GetAsync(“http://www.google.com”) .ConfigureAwait(continueOnCapturedContext: false); // This is the continuation […]

返回任务或等待和ConfigureAwait(false)

假设有一个像这样的方法的服务库 public async Task GetPersonAsync(Guid id) { return await GetFromDbAsync(id); } 遵循SynchronizationContext的最佳实践最好使用 public async Task GetPersonAsync(Guid id) { return await GetFromDbAsync(id).ConfigureAwait(false); } 但是当你只有一个操作(我认为)最好直接返回任务。 请参阅异步方法的结尾,我应该返回还是等待? public Task GetPersonAsync(Guid id) { return GetFromDbAsync(id); } 在最后一种情况下,您不能使用ConfigureAwait(false),因为不等待该方法。 什么是最佳解决方案(以及为什么)?

如何调用WebBrowser导航来浏览一些url?

要收集网页上的信息,我可以使用WebBrowser.Navigated事件。 首先,导航到url: WebBrowser wbCourseOverview = new WebBrowser(); wbCourseOverview.ScriptErrorsSuppressed = true; wbCourseOverview.Navigate(url); wbCourseOverview.Navigated += wbCourseOverview_Navigated; 然后在调用Navigated时处理网页: void wbCourseOverview_Navigated(object sender, WebBrowserNavigatedEventArgs e) { //Find the control and invoke “Click” event… } 当我尝试通过字符串数组的url时,困难的部分出现了。 foreach (var u in courseUrls) { WebBrowser wbCourseOverview = new WebBrowser(); wbCourseOverview.ScriptErrorsSuppressed = true; wbCourseOverview.Navigate(u); wbCourseOverview.Navigated += wbCourseOverview_Navigated; } 在这里,因为页面加载需要时间, wbCourseOverview_Navigated永远不会达到wbCourseOverview_Navigated 。 我试图在C#5中使用async await 。 […]

如何取消等待Task.Delay()?

正如您在此代码中看到的: public async void TaskDelayTest() { while (LoopCheck) { for (int i = 0; i < 100; i++) { textBox1.Text = i.ToString(); await Task.Delay(1000); } } } 我希望它将文本框设置为一秒钟的字符串值,直到我将LoopCheck值设置为false 。 但它的作用是它为所有人创建了所有迭代的内容,即使我将LoopCheck值设置为false,它仍然会执行它异步执行的操作。 我想在设置LoopCheck=false时取消所有等待的Task.Delay()迭代。 我该如何取消?

如何处理xUnit .net的Assert.Throws 中的Tasks抛出的exception?

以下异步xUnit.net测试使用标记有async修饰符的lambda失败,因为报告没有抛出exception: [Theory, AutoWebData] public async Task SearchWithNullQueryThrows( SearchService sut, CancellationToken dummyToken) { // Fixture setup // Exercise system and verify outcome Assert.Throws(async () => await sut.SearchAsync(null, dummyToken)); // Teardown } 为了确保实际抛出ArgumentNullException我明确地使用了try-catch块。 它工作,但结果代码不干净(与第一次测试相比): [Theory, AutoWebData] public async Task SearchWithNullQueryThrows( SearchService sut, CancellationToken dummyToken) { // Fixture setup var expected = typeof(ArgumentNullException); Type actual = null; // […]