Tag: async await

使用异步套接字的多个套接字连接

我有以下代码,使TCP套接字连接到多个端点,如下所示: private async void button1_Click(object sender, EventArgs e) { var listofIps = new List { “192.168.168.193”, “192.168.168.221” }; foreach (var ip in listofIps) { IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), 4001); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sockets.Add(client); await client.ConnectTaskAsync(remoteEP); await ReadAsync(client); } } async Task ReadAsync(Socket s) { var args = new SocketAsyncEventArgs(); args.SetBuffer(new […]

在ASP.NET应用程序中执行多个线程上的方法

我有一个ASP.NET应用程序,其中一个请求调用6个非常慢的方法。 这些方法不是异步的,我没有时间重写和测试它们。 如何在6个线程上运行这6个方法,然后对结果进行聚合? 我在.NET 4.5上。

如何将任务链接到它的前一个实例?

希望将任务链接到先前的实例(如果存在)。 目前,两者都是同时执行的。 适用于一项任务的初始代码: private async void MenuMediaAddFiles_OnClick(object sender, RoutedEventArgs e) { var dialog = GetDefaultOpenFileDialog(); using (dialog) { if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (var progress = new SimpleProgress(this)) { int addFiles = await _context.AddFiles(dialog.FileNames, progress); Console.WriteLine(“Files added: {0}”, addFiles); } } } } 试图使它工作失败: Task _files; private async void MenuMediaAddFiles_OnClick(object sender, RoutedEventArgs e) { […]

如何在Windows 10中的c#中的异步方法中从返回的任务中提取数据

如何从下面的foreach循环中的getResponseFromUrl的返回值中提取数据:这里我无法从返回的值中提取数据。 我正在windows 10通用应用程序开发中构建一个应用程序。 var response = NetworkingCalls.getResponseFromUrl(url, requestDictionary); foreach (KeyValuePair item in response) { Util.debugLog(item.Key.ToString(), item.Value.ToString()); } 这是返回字典的模型代码 using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Storage.Streams; using Windows.Web.Http; namespace App2.WrittenLibraries { class NetworkingCalls { public async static Task<Dictionary> getResponseFromUrl(string urlString, Dictionary requestDictionary) { var client = new HttpClient(); Uri url = new Uri(urlString); var requestToSend […]

使用asyn和await的.net 4.5中的异步TCP服务器,正在发生数据丢失

我必须使用async来实现asnet tcp在.net 4.5中的服务并通过引用我实现服务器的链接来等待 我的服务器代码如下 public class AsyncEchoServer { private int _listeningPort; public AsyncEchoServer( int port) { _listeningPort = port; } public async void Start() { IPAddress ipAddre = IPAddress.Parse(“192.168.2.4”); TcpListener listener = new TcpListener(ipAddre, _listeningPort); listener.Start(); LogMessage(“Server is running”); while (true) { try { var tcpClient = await listener.AcceptTcpClientAsync(); HandleConnectionAsync(tcpClient); } catch (Exception exp) { […]

如何在后台实现UDP监听器? (可用于log4net)

我想在后台运行这个UDPListener : // launch this in a background thread private static void UDPListen() { IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) using( var udpClient = new UdpClient(10000)) { while (true) { var buffer = udpClient.Receive(ref remoteEndPoint); var loggingEvent = System.Text.Encoding.Unicode.GetString(buffer); // … } } } 我可以将它放在Task.Run()并在while()循环中运行吗?

同步到异步调度:如何避免死锁?

我正在尝试创建一个具有同步方法的类,并调用其他一些异步的库方法。 出于这个原因,我使用Task.Result等待异步操作完成。 我的方法由WPF app以同步方式调用。 这导致僵局。 我知道最好的方法是使我的所有方法都异步,但我的情况要求它们是同步的。 另一方面,他们使用异步的其他库。 我的问题是:如何在这种情况下避免陷入僵局? 重现步骤: 用户点击应用中的按钮(方法Button1_OnClick ) 此方法创建IPlugin的实例,然后调用其方法RequestSomething() 然后,此方法以这种方式调用异步库: asyncTarget.MethodFromAsyncLibrary(“HelloFromPlugin”).Result 该库调用它的方法NotifyNewValueProgressAsync() NotifyNewValueProgressAsync()将调用委托给WPF应用程序 由于UI上下文被此行阻止了asyncTarget.MethodFromAsyncLibrary(“HelloFromPlugin”).Result步骤5中的回调导致死锁。 请参阅下面的代码示例和相关注释: public class SyncAdapterPlugin : IPlugin, IProgressAsyncHandler { //Constructor and fields are omitted here //This method is called from UI context by WPF application and it delegates synchronous call to asynchronous method string IPlugin.RequestSomething() { //In order to […]

并行请求刮取网站的多个页面

我想用一个包含大量有趣数据页面的网站,但由于源非常大,我想multithreading并限制过载。 我使用Parallel.ForEach来启动10个任务的每个块,然后在main for循环中等待,直到活动线程的数量开始下降到阈值以下。 为此我使用活动线程的计数器,我在使用WebClient启动新线程时递增,并在触发WebClient的DownloadStringCompleted事件时递减。 最初的问题是如何使用DownloadStringTaskAsync而不是DownloadString并等待Parallel.ForEach启动的每个线程都已完成。 这已通过一种解决方法解决:主要foor循环中的计数器( activeThreads )和Thread.Sleep 。 使用await DownloadStringTaskAsync而不是DownloadString应该通过在等待DownloadString数据到达时释放线程来提高速度吗? 回到原来的问题,是否有办法更优雅地使用TPL,而没有涉及计数器的解决方法? private static volatile int activeThreads = 0; public static void RecordData() { var nbThreads = 10; var source = db.ListOfUrls; // Thousands urls var iterations = source.Length / groupSize; for (int i = 0; i RecordUri(item)); //I want to wait here until process […]

将异步函数存储为变量

我有一个类似于这个问题的问题,但不同之处在于我在处理异步函数。 所以问题说我想在变量中存储一个方法(以后再调用它) 在syncrhonous函数的情况下 private delegate void eventmethod(); //(for a function without arguments and return void) private eventmethod MySavedEvent; void D() { } MySavedEvent = D; MySavedEvent(); 但是如果该function实际上会发生什么 Task D(); 如何在那里定义代理?

API请求WaitingForActivation“尚未计算”错误

我使用的是Poloniex C#API代码: https : //github.com/Jojatekok/PoloniexApi.Net 在我的控制台应用程序上获取余额的请求正在运行,我进行API调用并且余额返回,但在我的Windows窗体应用程序上,它没有等待余额: Id = 14, Status = WaitingForActivation, Method = “{null}”, Result = “{Not yet computed}” 使用此代码时: PoloniexClient polo_client { get; set; } private void Main(){ polo_client = new PoloniexClient(ApiKeys.PublicKey, ApiKeys.PrivateKey); var balance_task = getLatestWalletAmounts(); balance_task.Wait(); // doesn’t get past here on my Forms app if (balance_task.IsCompleted){ // gets to here […]