Tag: async await

Async-Await的真正优势是什么?

早些时候我发布了与在客户端或服务中应用Async-Await相关的问题。 在继续讨论这个问题之前,请先阅读这个问题,因为它与问题紧密相关。 基于答案,我已经测试了C#4.0(TPL)和C#5.0(Async – Await)的代码。 我使用服务提供的方法的异步和同步版本调用服务,并比较每种情况下使用的线程数。 以下是我用于测试所用资源的代码: 主要方法 List<Task> tasksList = new List<Task>(); List asyncThreads = new List(); List tplThreads = new List(); Stopwatch watch = new Stopwatch(); watch.Start(); // Call the Async version of the method for (int i = 0; i < 500; i++) { tasksList.Add(GetNameFromServiceAsync("Input" + i.ToString(), asyncThreads)); } Task.WaitAll(tasksList.ToArray()); watch.Stop(); foreach […]

将基于事件的模式转换为异步CTP模式

_fbClient.GetCompleted += new EventHandler(OnFetchPageNotification); _fbClient.GetAsync(_kNotificationPath, new Dictionary { { “access_token”, _kPageAccessToken } }); 如何将上面的代码转换为wp7中的等待代码: object = await _fbClient.GetAsync(_kNotificationPath, new Dictionary { { “access_token”, _kPageAccessToken } }); 我也有CTP安装和任务并行库。

解释async再次等待

这是我的事件处理程序代码: protected async void TestrunSaveExecute() { bool saveResult = await SaveTestRunAsync(); } 为了保持UI响应,我使用了async / await方法。 根据我的理解,我现在可以在SaveTestRunAsync()进行一些冗长的操作而不会阻塞UI,因为它是通过使用await关键字解耦的。 private async Task SaveTestRunAsync() { //System.Threading.Thread.Sleep(5000); –> this blocks the UI await Task.Delay(5000); // this doesn’t block UI return true; } 你能解释一下为什么对Thread.Sleep的调用仍会阻止UI,而Task.Delay却没有?

无法等待异步扩展方法

情况非常简单 – 我编写了一个扩展方法,并将其与返回类型Task进行异步。 但是当我尝试使用await调用它时,编译器会抛出一个错误,表明扩展方法根本不被识别为异步。 这是我的代码: public static async Task<NodeReference> CreateWithLabel(this GraphClient client, T source, String label) where T: class { var node = client.Create(source); var url = string.Format(ConfigurationManager.AppSettings[configKey] + “/node/{0}/labels”, node.Id); var serializedLabel = string.Empty; using (var tempStream = new MemoryStream()) { new DataContractJsonSerializer(label.GetType()).WriteObject(tempStream, label); serializedLabel = Encoding.Default.GetString(tempStream.ToArray()); } var bytes = Encoding.Default.GetBytes(serializedLabel); using (var […]

‘await’运算符只能与异步lambda表达式一起使用

我正在尝试将文件列表复制到目录中。 我正在使用async / await。 但我一直在收到这个编译错误 ‘await’运算符只能在异步lambda表达式中使用。 考虑使用’async’修饰符标记此lambda表达式。 这就是我的代码 async Task CopyFilesToFolder(List fileList, IProgress progress, CancellationToken ct) { int totalCount = fileList.Count; int processCount = await Task.Run(() => { int tempCount = 0; foreach (var file in fileList) { string outputFile = Path.Combine(outputPath, file); await CopyFileAsync(file, outputFile); //<– ERROR: Compilation Error ct.ThrowIfCancellationRequested(); tempCount++; if (progress != […]

如何使用async-await模式初始化对象

我正在尝试在我的服务类中遵循RAII模式,这意味着当构造一个对象时,它会被完全初始化。 但是,我遇到了异步API的困难。 有问题的类的结构如下所示 class ServiceProvider : IServiceProvider // Is only used through this interface { public int ImportantValue { get; set; } public event EventHandler ImportantValueUpdated; public ServiceProvider(IDependency1 dep1, IDependency2 dep2) { // IDependency1 provide an input value to calculate ImportantValue // IDependency2 provide an async algorithm to calculate ImportantValue } } 我的目标是摆脱ImportantValue getter中的副作用,使其成为线程安全的。 现在, […]

如何为HttpWebRequest定义更积极的超时?

在可移植类库中,我有以下方法将数据发布到特定的Url。 该方法效果很好。 但是我想指定一个更积极的超时(默认为100秒)。 考虑到来自可移植类库的HttpWebRequest类没有Timeout属性,如何在超过几秒的时间内确保调用被放弃? public async Task PostAsync(Uri uri, string data) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = “POST”; request.ContentType = “application/x-www-form-urlencoded”; using (Stream requestStream = await request.GetRequestStreamAsync()) { byte[] postBytes = Encoding.UTF8.GetBytes(data); requestStream.Write(postBytes, 0, postBytes.Length); } HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); return new HttpResponse(response.StatusCode, await new StreamReader(response.GetResponseStream()).ReadToEndAsync()); }

异步方法中的警告消息说它缺少等待运算符

我在我的asp.net mvc 4应用程序中有一个excel下载。 单击导出按钮时,将调用以下控制器方法。 因为我需要它是异步完成的,所以我在这里使用异步并等待。 public async Task GenerateReportExcel() { ExcelGenerator excel = new ExcelGenerator(); var filePath = await excel.ReportExcelAsync(midyearReportViewModel); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = “text/plain”; response.AddHeader(“Content-Disposition”, string.Format(“attachment;filename={0}.xlsx;”, PdaResource.ReportFileName)); response.TransmitFile(filePath); response.Flush(); response.End(); return PartialView(“_MidYearReportPartial”, midyearReportViewModel); } 此方法调用excel生成器方法ReportExcelAsync,如下所示 public async Task ReportExcelAsync(MidYearReportViewModel _midyearAnnualviewModel) { string fileName = “MidYearReport”; string finalXcelPath = string.Empty; string […]

MVC4 .NET 4.5异步操作方法不重定向

我正在尝试在我的MVC 4应用程序中实现任务操作方法。 一切都在后面工作,但它没有重定向。 public class AccountController : AsyncController { [HttpPost] [AllowAnonymous] public async Task Login(LoginModel model, string returnUrl) { var client = new ClientHelper(“login”); account = await client.CallActionType(EnumHelpers.HttpType.Post, model); if (account != null) { validLogin = true; } return Redirect(returnUrl); // This is called but the page does not redirect, just sits a load } […]

了解TaskScheduler.Current的行为

这是一个简单的WinForms应用程序: using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { var ts = TaskScheduler.FromCurrentSynchronizationContext(); await Task.Factory.StartNew(async () => { Debug.WriteLine(new { where = “1) before await”, currentTs = TaskScheduler.Current, thread = […]