Tag: async await

同时从同一个SslStream中读取?

我目前正在从SslStream中读取XML数据。 该流来自TcpClient对象。 using (XmlReader r = XmlReader.Create(sslStream, new XmlReaderSettings() { Async = true })) { while (await r.ReadAsync()) { ResetStream = false; switch (r.NodeType) { case XmlNodeType.XmlDeclaration: … break; case XmlNodeType.Element: … 另外,我想直接从TcpClient读取每个位和字节,无论它是否是XML数据。 如何两次读取相同的流? 是否可以使用XmlReader读取它并以某种方式转储流内容? 我想看看来自流的内容以及如何通过XmlReader解析它以进行调试。 更新: 我想保持一个流运行,而不是有两个独立的流。 由于我已经拥有了数据,因此在我的应用程序中将它再次存储在内存中是没有意义的。

实现是否会改变等待的行为?

Await关键字与等待类型一起使用(.NET附带现有的两种类型, Task和Task )。 但是,可以编写自己的等待类型。 msdn博客文章指出: 你可以想到以下代码: await FooAsync(); RestOfMethod(); 与此类似: var t = FooAsync(); var currentContext = SynchronizationContext.Current; t.ContinueWith(delegate { if (currentContext == null) RestOfMethod(); else currentContext.Post(delegate { RestOfMethod(); }, null); }, TaskScheduler.Current); 上面的(伪)代码是否遵循awaitable类型的实现(例如Task ),或者它可能只是编译器处理await关键字右侧的任何等待类型的方式? 在下面的评论部分,有一篇文章解释了TaskScheduler和SynchronizationContext之间的区别。 主要区别在于SynchronizationContext是使用委托的一般机制,而TaskScheduler特定于并且适用于任务(您可以使用TaskScheduler.FromCurrentSynchronizationContext获取包装SynchronizationContext的TaskScheduler)。 这就是为什么等待任务考虑到两者,首先检查SynchronizationContext(作为大多数UI框架支持的更一般的机制),然后回退到TaskScheduler。 等待不同类型的对象可能会选择首先使用SynchronizationContext,然后再回退到特定于该特定类型的其他某种机制。 如果我正确理解了最后一句,这意味着我可以在continueWith方法中放置我想要的任何委托(我的意思是上面代码示例中的t.ContinueWith调用),即修改await在与我的自定义等待对象一起使用时的工作方式。 万一你想了解更多: http : //blogs.msdn.com/b/pfxteam/archive/2009/09/22/9898090.aspx

异步方法不立即返回

我正在使用此解决方案: 如何正确编写异步方法? 但是,异步方法似乎不会立即返回,而是需要一段时间。 这里是 class Program { static void Main(string[] args) { Debug.WriteLine(“Calling DoDownload”); var downloadTask = DoDownloadAsync(); Debug.WriteLine(“DoDownload done”); downloadTask.Wait(); //Waits for the background task to complete before finishing. } private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync(“http://www.google.com/”); Debug.WriteLine(txt); } } 在下载文本之前正在打印“DoDownload Done”,但这需要一段时间(我认为它正在等待下载完全返回打印它。)我做错了什么?

FromBluetoothAddressAsync IAsyncOperation不包含“GetAwaiter”错误的定义

我正在研究一个简单的流行语。 我一直在提到这段代码 我在视觉工作室2017工作。 我的核心代码如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Threading; using Windows.Devices.Bluetooth.Advertisement; using Windows.Devices.Bluetooth; using Windows.Devices; using Windows.Foundation; using Windows; namespace WindowsFormsApp2 { public partial class Form1 : Form { private BluetoothLEAdvertisementWatcher watcher; public Form1() { InitializeComponent(); watcher = new BluetoothLEAdvertisementWatcher(); […]

使用ConfigureAwait(false)进行私有异步方法?

我有公共async方法,它调用3个不同的API来获取一些数据,然后将响应发布到下一个API。 现在根据Stephen cleary的文章来避免僵局: 1.在“库”异步方法中,尽可能使用ConfigureAwait(false)。 2.不要阻止任务; 一直使用async。 我想知道私有异步方法是否也是如此? 我在调用private异步方法时是否需要使用ConfigureAwait(false) ? 所以沿途就行了 public async Task ProcessAsync(ServiceTaskArgument arg) { // do i need to use ConfigureAwait here while calling private async method? var response1 = await GetAPI1().ConfigureAwait(false); // do i need to use ConfigureAwait here while calling private async method? var response2= await PostAPI2(response1).ConfigureAwait(false); // do i need […]

为什么有些异步方法需要返回类型的Task,而有些则不需要

在Microsoft的此示例中 ,该方法的返回类型为Task 例1: async Task AccessTheWebAsync() { // You need to add a reference to System.Net.Http to declare client. HttpClient client = new HttpClient(); // GetStringAsync returns a Task. That means that when you await the // task you’ll get a string (urlContents). Task getStringTask = client.GetStringAsync(“http://msdn.microsoft.com”); // You can do work here that doesn’t […]

async等待执行windows phone 8

我是异步的新手,等待编程风格。 如何解决以下问题: 我先调用下面的代码。 这里的问题是第一行正在等待填充categoriesvm.Categorieslist哪个需要,但它没有,但第二行被调用。 (我认为这是await的默认行为) 如何在第一行填充categoriesvm.Categorieslist时确保仅调用第二行? protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { categoriesvm.GetCategories(); BookCategories.DataContext = from vm in categoriesvm.Categorieslist select vm; } 在上面的代码中,当我执行第一行时,它会进入下面,其中Categorieslist是我上面访问的列表。 public async void GetCategories() { Categorieslist = new ObservableCollection(await PhoneClient.GetDefaultCategories()); } phoneclient在下面 public class PhoneClient { private static readonly HttpClient client; public static Uri ServerBaseUri { get { return new Uri(“http://169.254.80.80:30134/api/”); } […]

C#中的异步下载文件

我对C#中的异步操作有疑问。 假设我有一些像这样的代码: public async void Download(string[] urls) { for(int i = 0; i < urls.Length; i++); { await DownloadHelper.DownloadAsync(urls[i], @"C:\" + i.ToString() + ".mp3"); } } 但是这段代码并没有真正异步下载文件。 它开始从第一个URL下载文件,然后等待此操作。 然后它开始从第二个URL下载文件……依此类推。 从而逐个下载文件,我想让它们同时开始下载。 我怎么能这样做?

使用HttpClient.GetAsync方法的LINQ(Skip和Take)方法来提高性能?

我使用以下代码来检索JSON提要的内容,如您所见,我使用了分页技术和Skip and Take方法,如下所示: [HttpGet(“[action]”)] public async Task MyMethod(int page) { int perPage = 10; int start = (page – 1) * perPage; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(“externalAPI”); MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue(“application/json”); client.DefaultRequestHeaders.Accept.Add(contentType); HttpResponseMessage response = await client.GetAsync(client.BaseAddress); string content = await response.Content.ReadAsStringAsync(); IEnumerable data = JsonConvert.DeserializeObject<IEnumerable>(content); myPaginatedReturnedData datasent […]

在递归函数中使用Async / Await时控制任务总数

我写了这段代码。 它通过进行REST调用以递归方式在Web系统中创建文件夹。 所以基本上,它为根节点创建一个文件夹,然后并行地并递归地调用自己获取所有子节点。 (为每个孩子) 代码唯一的问题是,如果一个节点也有子节点,或者如果层次结构太深,那么我开始得到“TaskCancellation”错误。 我已经尝试将超时增加到10分钟..但这并没有解决问题。 所以我的问题是如何开始说出50个任务,然后等待某些东西被释放,只有当有50个开放槽时才能继续。 目前我认为我的代码正在创建任务,没有任何限制,因为流经层次结构。 public async Task CreateSPFolder(Node node, HttpClient client, string docLib, string currentPath = null) { string nodeName = Uri.EscapeDataString(nodeName); var request = new { __metadata = new { type = “SP.Folder” }, ServerRelativeUrl = nodeName }; string jsonRequest = JsonConvert.SerializeObject(request); StringContent strContent = new StringContent(jsonRequest); strContent.Headers.ContentType = MediaTypeHeaderValue.Parse(“application/json;odata=verbose”); […]