Tag: task parallel library

在异步方法中返回和等待任务之间的区别

以下方法之间有什么区别吗? 一个比另一个好吗? public static async Task SendAsync1(string to, string subject, string htmlBody) { // … await smtp.SendMailAsync(message); // No return statement } public static Task SendAsync2(string to, string subject, string htmlBody) { // … return smtp.SendMailAsync(message); } 这个方法将从MVC控制器方法调用; 例如: public async Task RegisterUser(RegisterViewModel model) { // … await Mailer.SendAsync(user.Email, subject, body); return View(model); }

AspNetSynchronizationContext并等待ASP.NET中的延续

在异步ASP.NET Web API控制器方法中await后,我注意到一个意外的(我会说,一个冗余的)线程切换。 例如,下面我希望在#2和3#位置看到相同的ManagedThreadId ,但最常见的是我在#3处看到了不同的线程: public class TestController : ApiController { public async Task GetData() { Debug.WriteLine(new { where = “1) before await”, thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); await Task.Delay(100).ContinueWith(t => { Debug.WriteLine(new { where = “2) inside ContinueWith”, thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); }, TaskContinuationOptions.ExecuteSynchronously); //.ConfigureAwait(false); Debug.WriteLine(new { where = […]

在WinForms上使用async / await访问Task.Run中的UI控件

我在WinForms应用程序中有以下代码,只有一个按钮和一个标签: using System; using System.IO; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { await Run(); } private async Task Run() { await Task.Run(async () => { await File.AppendText(“temp.dat”).WriteAsync(“a”); label1.Text = “test”; }); } } } 这是我正在处理的实际应用程序的简化版本。 […]

具有multithreading或任务的进程队列

我有一个电话消息应用程序,其中有许多消息要处理。因为电话端口是有限的,所以消息将先进行处理。 每条消息都有一个标记’Acknowledge’,表示处理的是哪一个。 当然它被初始化为假。 我想将所有消息放入队列,然后使用多个线程或任务处理它们。 public class MessageQueue { public Queue MessageWorkItem { get; set; } public Messages Message { get; set; } public MessageQueue() { MessageWorkItem = new Queue(); Message = new Messages(); } public void GetMessageMetaData() { try { // It is just a test, add only one item into the queue Message.MessageID = […]

在主UI线程的Continuation中,SynchronizationContext.Current为null

我一直在尝试在Winforms应用程序中追踪以下问题: SynchronizationContext.Current在任务的继续(即.ContinueWith )中为空,它在主线程上运行(我希望当前的同步上下文是System.Windows.Forms.WindowsFormsSynchronizationContext )。 以下是演示此问题的Winforms代码: using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); TaskScheduler ts = TaskScheduler.FromCurrentSynchronizationContext(); // Get the UI task scheduler // This line is required to see the issue (Removing this causes the problem to go away), since […]

列出线程安全

我使用以下代码 var processed = new List(); Parallel.ForEach(items, item => { processed.Add(SomeProcessingFunc(item)); }); 上面的代码线程安全吗? 处理后的列表是否有可能被破坏? 或者我应该在添加之前使用锁? var processed = new List(); Parallel.ForEach(items, item => { lock(items.SyncRoot) processed.Add(SomeProcessingFunc(item)); }); 谢谢。

再访问​​Task.ConfigureAwait(continueOnCapturedContext:false)

太久阅读了。 使用Task.ConfigureAwait(continueOnCapturedContext: false)可能会引入冗余线程切换。 我正在寻找一致的解决方案。 长版。 ConfigureAwait(false)背后的主要设计目标是尽可能减少用于await冗余SynchronizationContext.Post连续回调。 这通常意味着更少的线程切换和更少的UI线程工作。 但是,它并不总是如何运作。 例如,有一个实现SomeAsyncApi API的第三方库。 请注意,由于某些原因,此库中的任何位置都不使用ConfigureAwait(false) : // some library, SomeClass class public static async Task SomeAsyncApi() { TaskExt.Log(“X1”); // await Task.Delay(1000) without ConfigureAwait(false); // WithCompletionLog only shows the actual Task.Delay completion thread // and doesn’t change the awaiter behavior await Task.Delay(1000).WithCompletionLog(step: “X1.5”); TaskExt.Log(“X2”); return 42; } // logging helpers […]

TaskCreationOptions.LongRunning选项和ThreadPool

TPL使用任务计划程序来协调任务。 根据官方文档 ,默认任务调度程序使用线程池,但如果出现TaskCreationOptions.LongRunning选项,则它将为该任务创建专用线程(A)。 问题:截至目前,Visual Studio 2010的MSDN文档尚未就绪,当前的在线MSDN尚未最终确定; 有谁知道(A)是真还是假?

通用FromEvent方法

使用新的async / await模型,生成一个在事件触发时完成的Task非常简单; 你只需要遵循这种模式: public class MyClass { public event Action OnCompletion; } public static Task FromEvent(MyClass obj) { TaskCompletionSource tcs = new TaskCompletionSource(); obj.OnCompletion += () => { tcs.SetResult(null); }; return tcs.Task; } 这允许: await FromEvent(new MyClass()); 问题是您需要为每个要await类中的每个事件创建一个新的FromEvent方法。 这可能会变得非常快,而且它主要只是样板代码。 理想情况下,我希望能够做到这样的事情: await FromEvent(new MyClass().OnCompletion); 然后我可以为任何实例上的任何事件重用相同的FromEvent方法。 我花了一些时间来尝试创建这样的方法,并且存在许多障碍。 对于上面的代码,它将生成以下错误: 事件’Namespace.MyClass.OnCompletion’只能出现在+ =或 – =的左侧 据我所知,没有办法通过代码传递这样的事件。 所以,下一个最好的事情似乎是尝试将事件名称作为字符串传递: await FromEvent(new […]

如何在超时期限后取消任务等待

我正在使用此方法以编程方式实例化Web浏览器,导航到URL并在文档完成时返回结果。 如果文档加载时间超过5秒,我将如何能够停止Task并让GetFinalUrl()返回null ? 我见过很多使用TaskFactory例子,但是我无法将它应用于这段代码。 private Uri GetFinalUrl(PortalMerchant portalMerchant) { SetBrowserFeatureControl(); Uri finalUri = null; if (string.IsNullOrEmpty(portalMerchant.Url)) { return null; } Uri trackingUrl = new Uri(portalMerchant.Url); var task = MessageLoopWorker.Run(DoWorkAsync, trackingUrl); task.Wait(); if (!String.IsNullOrEmpty(task.Result.ToString())) { return new Uri(task.Result.ToString()); } else { throw new Exception(“Parsing Failed”); } } // by Noseratio – http://stackoverflow.com/users/1768303/noseratio static async Task DoWorkAsync(object[] […]