Tag: 异步

如何在C#3.5中取消异步委托?

我上下搜索谷歌,但我找不到关于该主题的任何适当信息。 我想做的是: 用户在文本框中键入单个搜索字符串。 我等了0.5秒然后我开始BeginInvoke我的委托指向搜索方法。 如果用户再次键入char,我想取消搜索并开始新的搜索,并输入新的字符串。 不得阻止UI-Thread! 我怎么能用C#3.5做到这一点? 更新 : 查看 : private void OnTextChanged(…) { if (SearchFormatEvent != null) { ICollection collection = SearchFormatEvent(“MySearchString”); // Do stuff on the returned collection } } SearchProvider : // This is the delegate invoked for the async search taking the searchstring typed by the user public delegate ICollection […]

返工EventWaitHandle以异步等待信号

当调用EventWaitHandle.WaitOne时,我需要将当前代码更改为不阻止当前线程。 问题是我正在等待全系统事件。 我还没有找到任何适当的替代品。 码: EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.AutoReset, “Local event”, out screenLoadedSignalMutexWasCreated); StartOtherApp(); if (screenLoadedSignalMutexWasCreated) { isOtherAppFullyLoaded = handle.WaitOne(45000, true); if (isOtherAppFullyLoaded ) { // do stuff } else { // do stuff } handle.Dispose(); signalingCompleted = true; } else { isOtherAppFullyLoaded = false; throw new Exception(” “); } 我需要应用程序继续而不是停在我称之为WaitOne的行上,理想情况下会有等待。 我该如何实现呢?

减慢创建具有许multithreading的对象

我正在做一个产生数百个线程的项目。 所有这些线程都处于“hibernate”状态(它们被锁定在Monitor对象上)。 我注意到,如果我增加“hibernate”线程的数量,程序会非常慢。 “有趣”的是,看着任务管理器似乎线程数越多,处理器就越自由。 我已将问题缩小到对象创建。 有人可以向我解释一下吗? 我制作了一个小样本来测试它。 这是一个控制台程序。 它为每个处理器创建一个线程,并通过简单的测试(“新对象()”)测量它的速度。 不,“新的对象()”没有被淘汰(如果你不信任我,试试)。 主线程显示每个线程的速度。 按CTRL-C,该程序产生50个“睡眠”线程。 减速开始只有50个线程。 在任务管理器中,大约250个非常明显,CPU不是100%使用的(我的是82%)。 我已经尝试了三种锁定“hibernate”线程的方法:Thread.CurrentThread.Suspend()(坏,坏,我知道:-)),锁定已经锁定的对象和Thread.Sleep(Timeout.Infinite)。 一样的。 如果我使用新的Object()注释该行,并将其替换为Math.Sqrt(或没有任何内容),则问题不存在。 速度不随线程数而变化。 别人可以查一下吗? 有谁知道瓶颈在哪里? 啊……你应该在发布模式下测试它,不要从Visual Studio中启动它。 我在双处理器上使用XP sp3(没有HT)。 我用.NET 3.5和4.0测试了它(测试不同的框架运行时) namespace TestSpeed { using System; using System.Collections.Generic; using System.Threading; class Program { private const long ticksInSec = 10000000; private const long ticksInMs = ticksInSec / 1000; private const int […]

异步/等待模式会对次要工作单元造成性能损失吗?

我正在寻找关于异步/等待有意义的“工作负载阈值”(例如释放IO完成端口并避免线程饥饿)与工作单元执行过于简单/便宜之间的一些指导,因此同步执行是一个更好的选择。 换句话说,当与相对快速/资源廉价的工作单元结合使用时,async / await的使用是否会导致性能下降,并且简单地同步执行工作将是首选方法? 示例(所有在一个方法中,所有异步与等待): 保存对DB的一些小更新 使用ReadAsStreamAsync将非常小的文件上载读取到流中 使用CopyToAsync将读取流复制到文件流 使用FlushAsync写入器流

为什么async / await允许从List到IEnumerable的隐式转换?

我一直在玩async / await,发现了一些有趣的东西。 看看下面的例子: // 1) ok – obvious public Task<IEnumerable> GetAll() { IEnumerable doctors = new List { new DoctorDto() }; return Task.FromResult(doctors); } // 2) ok – obvious public async Task<IEnumerable> GetAll() { IEnumerable doctors = new List { new DoctorDto() }; return await Task.FromResult(doctors); } // 3) ok – not so obvious […]

等待没有异步/等待的异步HTTP请求的响应

我正在开发一个Windows Forms应用程序的插件,它可以在地图上显示终端的位置(在WebBrowser控件中)。 案例如下: 用户点击按钮(调用插件); 创建异步HTTP请求(确定终端的坐标); 随着所有回复的收到 – 地图应该显示给用户。 我写了代码: foreach (var terminal in terminals) { var webRequest = (HttpWebRequest)WebRequest.Create(GeoCoder.GeoCodeUrl + terminal.Address); var taskResp = Task.Factory.FromAsync(webRequest.BeginGetResponse, webRequest.EndGetResponse, terminal.Id); var taskResult = taskResp.ContinueWith(task => { // Parse the response }); runningTasks.Add(taskResult); } Task.WaitAll(runningTasks.ToArray()); // UI Thread blocks here! webBrowser1.DocumentText = … 它会阻止UI线程,因为我必须等到我才能显示地图之前得到所有响应(坐标)。 我想知道如何避免这种情况(没有同步的http请求)? PS我知道如何使用async / await但不能使用它们 – […]

传递* Awaitable *匿名函数作为参数

代码优先。 这就是我想要做的。 我很接近,但我想我只需要修改我在UpdateButton方法中定义参数的方式。 private async void UpdateButton(Action post) { if (!await post()) ErrorBox.Text = “Error posting message.”; } private void PostToTwitter() { UpdateButton(async () => await new TwitterAction().Post(“Hello, world!”)); } private void PostToFacebook() { UpdateButton(async () => await new FacebookAction().Post(“Hello, world!”)); } 不幸的是, !await post()不起作用,因为“Type’void’是不可行的。” 所以问题是,如何在此方法中定义我的参数以支持等待参数? 这是TwitterAction()。Post()的定义方式…… public virtual async Task Post(string messageId){…}

异步方法抛出exception

我目前在使用抛出exception的方法时遇到了一些问题,但我不确定原因。 该exception使我的应用程序崩溃。 System.NullReferenceException: Object reference not set to an instance of an object. at Myapp.AutoProcess.d__36.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__1(Object state) at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at […]

背景线上的火灾事件

道歉,我的问题和努力都不准确。 我正在开发具有不同组件的控制台应用程序。 现在我已将它们分离并希望它们使用异步发布者/订阅者方式进行交互; 类似于WPF。 所以在这种情况下,我将有一个主线程,它将始终存在,并根据请求它将调用事件,例如DataRequested将在后台线程上触发。 一旦后台线程完成进程,它将再次触发事件,例如DataCompleted,它应该返回到调用线程,即主线程。 我希望我的解释清楚。 So far I have coded below; where I have EventBroker. public class EventBroker { public static event EventHandler SubscriptionAdded; public static event EventHandler SubscriptionRemoved; private static volatile EventBroker instance; private static object syncRoot = new Object(); private static Dictionary<string, List> subscriptions; /// /// Initializes a new instance of […]

调用onclick on按钮将代码放入C#中的不同线程中

我有一个启动相机的按钮。 我想有时候开始拍摄相机,不按下按钮。 代码: private async void StartCamera() { if (!CameraList.HasItems) //——-> CameraList is in the UI { MessageArea.Text = “No cameras found; cannot start processing”; return; } // Clean leading/trailing spaces in API keys. Properties.Settings.Default.FaceAPIKey = Properties.Settings.Default.FaceAPIKey.Trim(); Properties.Settings.Default.EmotionAPIKey = Properties.Settings.Default.EmotionAPIKey.Trim(); Properties.Settings.Default.VisionAPIKey = Properties.Settings.Default.VisionAPIKey.Trim(); // Create API clients. _faceClient = new FaceServiceClient(Properties.Settings.Default.FaceAPIKey); _emotionClient = new EmotionServiceClient(Properties.Settings.Default.EmotionAPIKey); […]