Tag: 异步

parellellizing异步调用时如何获得最大出站请求?

通过Fiddler分析下面的代码,我意识到使用Parallel Extensions我可以获得最多2个出站请求: new string[] { “http://stackoverflow.com”, “http://superuser.com”, “http://serverfault.com”, “http://stackexchange.com” } .AsParallel() .Select(a => HttpWebRequest.Create(a).GetResponse()) .ToArray() ; 我应该使用什么方法来最大化出站请求的数量?

使用BeginXXX重写套接字和流代码到XXXAsync

我正在尝试将使用AsyncCallbacks的BeginXXX方法重写为使用async / await和XXXAsync方法的应用程序。 但是我在性能方面遇到了一些麻烦。 例如,这里是原始代码的片段,用于初始化一堆连接: … for (int i = 1; i <= _maxTcpClients; i++) { TcpClientState tt = new TcpClientState(new TcpClient(), i); try { tt.TcpClient.BeginConnect(Host, Port, ConnectCallback, tt); } catch (Exception ex) { Log.Debug( "Error on BeginConnect on RequestHandler (" + tt.HandlerId + ") request (" + tt.RequestId + ")", ex); CloseRequest(tt); } } […]

WPF ComboBox延迟过滤

考虑以下情况:有ComboBox和filterTextBox,然后用户在文本框中键入文本ComboBox项目源使用filter文本更新。 一切正常,但每个打字的字母都会进行过滤。 我希望在发生过滤之前添加延迟(在用户键入时不应用filter)。 最简单的方法是什么?

在Parallel.For内部调用的方法中,HttpContext为null

尝试了很多后发布这个问题。 做正常不是一种选择,因为我们需要在很短的时间内完成大量的处理。 我有GetDataFor() ,其中使用了HttpContext.Current 。 代码如下所示: public void SomeMethod() { var context = HttpContext.Current; Parallel.For(0, 100, i => { var data = GetDataFor(i, context); }); } public data GetDataFor(int i, HttpContext context) { Uri requestUri = null; if (HttpContext.Current != null) { requestUri = HttpContext.Current.Request.Url; sCookie = string.Format(“{0}”, HttpContext.Current.Request.Headers[“cookie”]); } else { requestUri = context.Request.Url; […]

多个管道服务器实例的异步NamedPipes

我正在使用本文中的代码,区别在于,在NamedPipeServerStream构造函数中, maxNumberOfServerInstances设置为-1 (具有相同管道名称的服务器实例的数量仅受系统资源限制) 异步侦听方法[侦听服务器类]: class PipeServer { string _pipeName; public void Listen(string PipeName) { try { // Set to class level var so we can re-use in the async callback method _pipeName = PipeName; // Create the new async pipe NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.In, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); // Wait for a connection pipeServer.BeginWaitForConnection […]

不等待时TaskCanceledException

每当我同步返回另一个任务而不是等待它时,我似乎得到一个TaskCanceledException ,遵循最后等待时的指导原则。 TaskCanceledException代码 public static class Download { public static Task FromYouTubeAsync(string videoUri) { using (var client = new HttpClient()) { return FromYouTubeAsync( () => client .GetStringAsync(videoUri), uri => client .GetByteArrayAsync(uri)); } } public async static Task FromYouTubeAsync( Func<Task> sourceFactory, Func<string, Task> downloadFactory) { string source = await // TaskCanceledException here sourceFactory() .ConfigureAwait(false); // find […]

C#进程无法访问文件,因为它正由另一个进程使用

请帮我解决我面临的问题。 我在C#中为xml文件编写了一个导入器。 每次运行导入时,我都需要从URL下载XML文件。 我已经下载了以下代码来下载它: var xmlPath = @”C:\Desktop\xxx.xml”; public void DownloadFile(string url, string saveAs) { using(var webClient = new WebClient()) { webClient.DownloadFileAsync(new Uri(url), saveAs); } } 和_downloader.DownloadFile(Config.FeedUrl, xmlPath); 调用方法。 Url位于配置文件( Config.FeedUrl )中。 然后,当我尝试GetProperties(xmlPath); 我得到exception“进程无法访问该文件,因为该文件正由另一个进程使用。 我确保目的地存在,但我不知道为什么我会收到此错误。 有人可以帮帮我吗? 谢谢

将同步zip操作转换为异步

我们有一个现有的库,其中一些方法需要转换为异步方法。 但是我不确定如何使用以下方法(error handling已被删除)。 该方法的目的是压缩文件并将其保存到磁盘。 (请注意,zip类不会公开任何异步方法。) public static bool ZipAndSaveFile(string fileToPack, string archiveName, string outputDirectory) { var archiveNameAndPath = Path.Combine(outputDirectory, archiveName); using (var zip = new ZipFile()) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; zip.Comment = $”This archive was created at {System.DateTime.UtcNow.ToString(“G”)} (UTC)”; zip.AddFile(fileToPack); zip.Save(archiveNameAndPath); } return true; } 实现可能如下所示: public static async Task ZipAndSaveFileAsync(string fileToPack, string archiveName, string […]

当所有关于大量任务

我需要你的帮助才能找到最佳解决方案。 这是我的原始代码: public async Task Test() { var tasks = new List(); string line; using (var streamReader = File.OpenText(InputPath)) { while ((line = streamReader.ReadLine()) != null) { tasks.Add(Process(line)); } } await Task.WhenAll(tasks.ToArray()); } private Task Process(string line) { return Task.Run(() => { Console.WriteLine(line); }); } 它将读取带有行的文件并按任务处理每一行。 但是,如果文件有100万行,那么任务数组就更大了,这段代码还是不错的? 或者我应该找到另一个解决方案 请帮我。 谢谢。

等待和异步阻止UI

我写了一个winforms应用程序来搜索磁盘上的文件(为了这个问题,哪个文件并不重要)。 问题是它甚至可以是100,000个文件。 所以这个操作需要时间。 我想要实现的是将搜索操作作为异步操作而不是阻止UI线程,这样表单就不会卡住。 我可以使用backgroundWorker执行此操作,但由于某些原因不能使用async \ await机制。 这是我的代码: private async void button_FindFiles_Click(object sender, EventArgs e) { await SearchFilesUtil.SearchPnrFilesAsync(this.textBox_mainDirectory.Text); MessageBox.Show(“After SearchPnrFilesAsync”); } public async static Task SearchPnrFilesAsync(string mainDir) { foreach (string file in Directory.EnumerateFiles(mainDir, “.xml”, SearchOption.AllDirectories)) { var fileContenet = File.ReadAllText(file); var path = Path.Combine(@”C:\CopyFileHere”, Path.GetFileName(file)); using (StreamWriter sw = new StreamWriter(path)) { await sw.WriteAsync(fileContenet); } […]