Search Results

Search found 1382 results on 56 pages for 'async await'.

Page 3/56 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Microsoft Async CTP for DDD9 UK Developer Conference - slides and source code now available

    - by Liam Westley
    Thanks to all the nice comments from people who attended my presentation at DDD9, and extra thanks to Jon Skeet, Mark Rendle and Mike Hadlow for coming on stage for the last ten minutes to help debate whether the Async CTP is the correct way to go to enhance C# 5.0. The presentation is available at Prezi.com http://prezi.com/gysz5nohltye, which I can recommend as a refreshing change to the more standard PowerPoint slidedecks. I've also uploaded all the code samples into a single ZIP file. You will need to install the Async CTP to be able to run them, and I would remind everyone that the current Async CTP is not compatible with either ASP.NET MVC 3 RTM or Visual Studio 2010 Service Pack 1 so you may need to use a test system of virtual machine to play with it! Source code - http://www.tigernews.co.uk/blog-twickers/ddd9/AsyncSrc.zip Again, thanks for all the positive feedback and the whole of the DDD team for putting on a fantastic conference for all the presenters and delegates.

    Read the article

  • Making a concurrent AJAX WCF Web Service request during an Async Postback

    - by nekno
    I want to provide status updates during a long-running task on an ASP.NET WebForms page with AJAX. Is there a way to get the ScriptManager to execute and process a script for a web service request concurrently with an async postback? I have a script on the page that makes a web service request. It runs on page load and periodically using setInterval(). It's running correctly before the async postback is initiated, but it stops running during the async postback, and doesn't run again until after the async postback completes. I have an UpdatePanel with a button to trigger an async postback, which executes the long-running task. I also have an instance of an AJAX WCF Web service that is working correctly to fetch data and present it on the page but, like I said, it doesn't fetch and present the data until after the async postback completes. During the async postback, the long-running task sends updates from the page to the web service. The problem is that I can debug and step through the web service and see that the status updates are correctly set, but the updates aren't retrieved by the client script until the async postback completes. It seems the Script Manager is busy executing the async postback, so it doesn't run my other JavaScript via setInterval() until the postback completes. Is there a way to get the Script Manager, or otherwise, to run the script to fetch data from the WCF web service during the async postback? I've tried various methods of using the PageRequestManager to run the script on the client-side BeginRequest event for the async postback, but it runs the script, then stops processing the code that should be running via setInterval() while the page request executes.

    Read the article

  • Making an AJAX WCF Web Service request during an Async Postback

    - by nekno
    I want to provide status updates during a long-running task on an ASP.NET WebForms page with AJAX. Is there a way to get the ScriptManager to execute and process a script for a web service request during an async postback? I have a script on the page that makes a web service request. It runs on page load and periodically using setInterval(). It's running correctly before the async postback is initiated, but it stops running during the async postback, and doesn't run again until after the async postback completes. I have an UpdatePanel with a button to trigger an async postback, which executes the long-running task. I also have an instance of an AJAX WCF Web service that is working correctly to fetch data and present it on the page but, like I said, it doesn't fetch and present the data until after the async postback completes. During the async postback, the long-running task sends updates from the page to the web service. The problem is that I can debug and step through the web service and see that the status updates are correctly set, but the updates aren't retrieved by the client script until the async postback completes. It seems the Script Manager is busy executing the async postback, so it doesn't run my other JavaScript via setInterval() until the postback completes. Is there a way to get the Script Manager, or otherwise, to run the script to fetch data from the WCF web service during the async postback? I've tried various methods of using the PageRequestManager to run the script on the client-side BeginRequest event for the async postback, but it runs the script, then stops processing the code that should be running via setInterval() while the page request executes.

    Read the article

  • Sending and receiving async over multiprocessing.Pipe() in Python

    - by dcolish
    I'm having some issues getting the Pipe.send to work in this code. What I would ultimately like to do is send and receive messages to and from the foreign process while its running in a fork. This is eventually going to be integrated into a pexpect loop for talking to interpreter processes. ` from multiprocessing import Process, Pipe def f(conn): cmd = '' if conn.poll(): cmd = conn.recv() i = 1 i += 1 conn.send([42 + i, cmd, 'hello']) if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=f, args=(child_conn,)) p.start() from pdb import set_trace; set_trace() while parent_conn.poll(): print parent_conn.recv() # prints "[42, None, 'hello']" parent_conn.send('OHHAI') p.join() `

    Read the article

  • How to write async background workers that work on WPF flowdocument

    - by iBe
    I'm trying to write a background worker that processes a flowdocument. I can't access the properties of flowdocument objects because of the thread verification. I tried to serialize the document and loaded it on the worker thread which actually solved the thread verfication issue. However, once the processing is complete I also need to use things like TextPointer objects. Those objects now point to a objects in the copy not the original. Can anyone suggest the best way to approach such background processing in WPF?

    Read the article

  • why the exception is not caught?

    - by Álvaro García
    I have the following code: List<MyEntity> lstAllMyRecords = miDbContext.MyEntity.ToList<MyEntity>(); foreach MyEntity iterator in lstMainRecord) { tasks.Add( TaskEx.Run(() => { try { checkData(lstAllMyRecords.Where(n => n.IDReference == iterator.IDReference).ToList<MyEntity>()); } catch CustomRepository ex) { //handle my custom repository } catch (Exception) { throw; } }) ); }//foreach Task.WaitAll(tasks.ToArray()); I get all the records from my data base and in the foreach loop, I group all the records that have the same IDReference. Thenk I check if the data is correct with the method chekData. The checkData method throw a custom exception if something is wrong. I would like to catch this exception to handle it. But the problem is that with this code the exceptions are not caught and all seem to work without errors, but I know that this is not true. I try to check only one group of records that I know that has problems. If I check only one group of registrers, the loop is execute once and then only task is created. In this case the exception is caught, but if I have many groups, then any exception s thrwon. Why when I only have one task the exception is caught and with many groups are not? Thanks.

    Read the article

  • Consuming Async SOA in a WebService Proxy By Anagha Desai

    - by JuergenKress
    Consider a scenario where an application is built using SOA Async processes and needs to be consumed in a WebService Proxy. In this blog, we will be demonstrating how to implement this use case. To achieve this, we will follow a two step process: Create an Async SOA BPEL process. Consume it in a WebService Proxy. Pre-requisite: Jdeveloper with SOA extension installed. Steps: To begin with step 1, create a SOA Application and name it SOA_AsyncApp. This invokes Create SOA Application wizard. In the wizard, choose composite with BPEL process in Step 3. Read the complete article here. SOA & BPM Partner Community For regular information on Oracle SOA Suite become a member in the SOA & BPM Partner Community for registration please visit www.oracle.com/goto/emea/soa (OPN account required) If you need support with your account please contact the Oracle Partner Business Center. Blog Twitter LinkedIn Facebook Wiki Technorati Tags: Anagha Desai,Async SOA,SOA Community,Oracle SOA,Oracle BPM,Community,OPN,Jürgen Kress

    Read the article

  • Visual Studio Async CTP

    - by Daniel Moth
    While most of the buzz at the recent PDC here at Microsoft's headquarters has been about Windows Azure and Windows Phone, there is a truly noteworthy technology that as a .NET developer (of any kind of application) you should pay attention to, even in its early technology preview stage: Visual Studio Async CTP. I could provide many more direct links, but you do not need them: just visit the home page of this technology to download whitepapers, watch videos on how this technology integrates with C# and with VB, (through the new async and await language keywords) as well as videos on how the technology works under the covers (based largely on the Task Parallel Library). More importantly, download the actual bits (they install on top of your Visual Studio 2010), which include many samples. Get ready for a revolution in Asynchronous Programming with C# and Visual Basic. Comments about this post welcome at the original blog.

    Read the article

  • My book is released – Async in C# 5

    - by Alex Davies
    I’m pleased to announce that my book “Async in C# 5″ has been published by O’Reilly! http://oreil.ly/QQBjO3 If you want to know about how to use async, and whether it’s important for your code, I thoroughly recommend reading it. It’s the best book about the subject I’ve ever written. In fact it’s probably the best book I’ve written full stop. I may have only written one book. It also has a very fetching parrot on the cover, which would make a very good addition to your bookshelf.

    Read the article

  • Multilevel asynchronous method call pattern in c#

    - by michajas
    Hi, I have design problem regarding async calls to method. I'd like to know best/good pattern to call async method, which calls another async method, which calls another async method :) In other words, I have WCF service reference created with async methods and I want to call them from another async method which is called by other async method. All this for non blocking GUI. Thanks!

    Read the article

  • Adding Async=true to the page- no side effects noticed.

    - by Michael Freidgeim
    Recently I needed to implement PageAsyncTask  in .Net 4 web forms application.According to http://msdn.microsoft.com/en-us/library/system.web.ui.pageasynctask.aspx"A PageAsyncTask object must be registered to the page through the RegisterAsyncTask method. The page itself does not have to be processed asynchronously to execute asynchronous tasks. You can set the Async attribute to either true (as shown in the following code example) or false on the page directive and the asynchronous tasks will still be processed asynchronously:<%@ Page Async="true" %>When the Async attribute is set to false, the thread that executes the page will be blocked until all asynchronous tasks are complete."I was worry about any site effects if I will set  Async=true on the existing page.The only documented restrictions, that I found are that@Async is not compatible with @AspCompat and Transaction attributes (from @ Page directive  MSDN article). In other words, Asynchronous pages do not work when the AspCompat attribute is set to true or the Transactionattribute is set to a value other than Disabled in the @ Page directiveFrom our tests we conclude, that adding Async=true to the page is quite safe, even if you don't always call Async tasks from the page

    Read the article

  • Cannot await 'Model.PersonalInfo'

    - by Gooftroop
    I have the following method in a DesignDataService class public async Task<T> GetData<T>(T dataObject) { var typeName = typeof(T).Name; switch (typeName) { case "PersonalInfo": var person = new PersonalInfo { FirstName = "Mickey", LastName = "Mouse" , Adres = new Address{Country="DLRP"} , }; return await person; } // end Switch } // GetData<T> How can I return a new PersonalInfo class from the DataService? For now I get the error Cannot await 'Model.PersonalInfo' Even when I change the return statement as follows return await person as Task; the error stays the same Thanks in advanced Danny

    Read the article

  • Dispatch request to an Async Servlet from managed bean generate exception

    - by Thang Pham
    when a button click, I need to have stuff running in my background, so I have a async Servlet. From my managed bean, if I do redirect, it works great (meaning that it execute my run() method inside my class that extends Runnable correctly). Like this String url = externalContext.getRequestContextPath() + "/ReportExecutionServlet"; externalContext.redirect(url); But if I switch to dispatch, like this externalContext.redirect("/ReportExecutionServlet"); it fail when I try to obtain the AsyncContext AsyncContext aCtx = request.startAsync(request, response); The error is below Caused By: java.lang.IllegalStateException: The async-support is disabled on this request: weblogic.servlet.internal.ServletRequestImpl Any idea how to fix this please? NOTE: This is how to execute my async servlet, just in case: AsyncContext aCtx = request.startAsync(request, response); //delegate long running process to an "async" thread aCtx.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent event) throws IOException { logger.log(Level.INFO, "ReportExecutionServlet handle async request - onComplete"); } @Override public void onTimeout(AsyncEvent event) throws IOException { logger.log(Level.WARNING, "ReportExecutionServlet handle async request - onTimeout"); } @Override public void onError(AsyncEvent event) throws IOException { logger.log(Level.SEVERE, "ReportExecutionServlet handle async request - onError"); } @Override public void onStartAsync(AsyncEvent event) throws IOException { logger.log(Level.INFO, "ReportExecutionServlet handle async request - onStartAsync"); } }); // Start another service ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10); executor.execute(new AsyncRequestReportProcessor(aCtx));

    Read the article

  • jQuery .ajax() call to page method works in FF only when async is false

    - by Steve
    I'm calling a page method using .ajax() and it works in IE8 whatever the value of async is. However, in FF3.6, it only works with async set to false. When async is set to true, in Firebug, I just see status aborted. The page validates. I can work with async set to false, but any clues as to why FF can't work with async set to true? $("[id$='_www']").click(function() { var hhh = false; $.ajax({ async: false, cache: false, type: "POST", url: "/abc/def.aspx/jkl", contentType: "application/json; charset=utf-8", dataType: "json", data: "{ 'eee': '" + window.location.href.match(/\d{1,3}$/) + "', 'ttt': '" + $("[id$='_zzz']").val() + "' }", success: function(msg) { $("#ggg").html(msg.d); }, error: function(xhr, err) { hhh = true; } }); return hhh; });

    Read the article

  • DDDSouthWest 4.0 26th May 2012 - Async 20/20 presentation

    - by Liam Westley
    As I wasn’t voted in with my nominated sessions I presented a 20/20 talk on the new async functionality coming with the .Net Framework.  This was based on the PechaKucha presentation format, where you have only 20 slides with only 20 seconds per slide, and it progresses automatically. It was the first I’d attempted, so thanks to the organisers for allowing me to have a go. Although creating the slide deck was definitely easier than a one hour presentation, it was much more stressful giving the talk by the end of the 6m 40s. I’m not going to upload the slide deck (it won’t make much sense) but I did record the audio and used the excellent Camtasia to create a video of the slide deck with that audio which you can watch over here, https://vimeo.com/42957952

    Read the article

  • Asynchronous Streaming in ASP.NET WebApi

    - by andresv
     Hi everyone, if you use the cool MVC4 WebApi you might encounter yourself in a common situation where you need to return a rather large amount of data (most probably from a database) and you want to accomplish two things: Use streaming so the client fetch the data as needed, and that directly correlates to more fetching in the server side (from our database, for example) without consuming large amounts of memory. Leverage the new MVC4 WebApi and .NET 4.5 async/await asynchronous execution model to free ASP.NET Threadpool threads (if possible).  So, #1 and #2 are not directly related to each other and we could implement our code fulfilling one or the other, or both. The main point about #1 is that we want our method to immediately return to the caller a stream, and that client side stream be represented by a server side stream that gets written (and its related database fetch) only when needed. In this case we would need some form of "state machine" that keeps running in the server and "knows" what is the next thing to fetch into the output stream when the client ask for more content. This technique is generally called a "continuation" and is nothing new in .NET, in fact using an IEnumerable<> interface and the "yield return" keyword does exactly that, so our first impulse might be to write our WebApi method more or less like this:           public IEnumerable<Metadata> Get([FromUri] int accountId)         {             // Execute the command and get a reader             using (var reader = GetMetadataListReader(accountId))             {                 // Read rows asynchronously, put data into buffer and write asynchronously                 while (reader.Read())                 {                     yield return MapRecord(reader);                 }             }         }   While the above method works, unfortunately it doesn't accomplish our objective of returning immediately to the caller, and that's because the MVC WebApi infrastructure doesn't yet recognize our intentions and when it finds an IEnumerable return value, enumerates it before returning to the client its values. To prove my point, I can code a test method that calls this method, for example:        [TestMethod]         public void StreamedDownload()         {             var baseUrl = @"http://localhost:57771/api/metadata/1";             var client = new HttpClient();             var sw = Stopwatch.StartNew();             var stream = client.GetStreamAsync(baseUrl).Result;             sw.Stop();             Debug.WriteLine("Elapsed time Call: {0}ms", sw.ElapsedMilliseconds); } So, I would expect the line "var stream = client.GetStreamAsync(baseUrl).Result" returns immediately without server-side fetching of all data in the database reader, and this didn't happened. To make the behavior more evident, you could insert a wait time (like Thread.Sleep(1000);) inside the "while" loop, and you will see that the client call (GetStreamAsync) is not going to return control after n seconds (being n == number of reader records being fetched).Ok, we know this doesn't work, and the question would be: is there a way to do it?Fortunately, YES!  and is not very difficult although a little more convoluted than our simple IEnumerable return value. Maybe in the future this scenario will be automatically detected and supported in MVC/WebApi.The solution to our needs is to use a very handy class named PushStreamContent and then our method signature needs to change to accommodate this, returning an HttpResponseMessage instead of our previously used IEnumerable<>. The final code will be something like this: public HttpResponseMessage Get([FromUri] int accountId)         {             HttpResponseMessage response = Request.CreateResponse();             // Create push content with a delegate that will get called when it is time to write out              // the response.             response.Content = new PushStreamContent(                 async (outputStream, httpContent, transportContext) =>                 {                     try                     {                         // Execute the command and get a reader                         using (var reader = GetMetadataListReader(accountId))                         {                             // Read rows asynchronously, put data into buffer and write asynchronously                             while (await reader.ReadAsync())                             {                                 var rec = MapRecord(reader);                                 var str = await JsonConvert.SerializeObjectAsync(rec);                                 var buffer = UTF8Encoding.UTF8.GetBytes(str);                                 // Write out data to output stream                                 await outputStream.WriteAsync(buffer, 0, buffer.Length);                             }                         }                     }                     catch(HttpException ex)                     {                         if (ex.ErrorCode == -2147023667) // The remote host closed the connection.                          {                             return;                         }                     }                     finally                     {                         // Close output stream as we are done                         outputStream.Close();                     }                 });             return response;         } As an extra bonus, all involved classes used already support async/await asynchronous execution model, so taking advantage of that was very easy. Please note that the PushStreamContent class receives in its constructor a lambda (specifically an Action) and we decorated our anonymous method with the async keyword (not a very well known technique but quite handy) so we can await over the I/O intensive calls we execute like reading from the database reader, serializing our entity and finally writing to the output stream.  Well, if we execute the test again we will immediately notice that the a line returns immediately and then the rest of the server code is executed only when the client reads through the obtained stream, therefore we get low memory usage and far greater scalability for our beloved application serving big chunks of data.Enjoy!Andrés.        

    Read the article

  • DDDNorth2 Bradford, 13th October 2012 - Async Patterns presentation and source code

    - by Liam Westley
    Many thanks to Andy Westgarth and his team for organising a fantastic conference at the rather elegant Bradford University School of Management. Also, a big congratulations to all the delegates who gave up there free time to come and hear us speak and who were, in general, enthusiastic and asked some cracking questions to keep us speakers on our toes. For those who attended my Async my source code and presentation are now available on GitHub, https://github.com/westleyl/DDDNorth2-AsyncPatterns If you are new to Git then the easiest client to install is GitHub for Windows, a graphical UI for accessing GitHub. Personally, I also have TortoiseGit installed – the file explorer add-in that works in a familiar manner to TortoiseSVN. As I mentioned during the presentation I have not included the sample data, the music files, in the source code placed on GitHub but I have included instructions on how to download them from http://silents.bandcamp.com and place them in the correct folders. What I forgot to mention is that Windows Media Player by default does not play Ogg Vorbis and Flac music files, however you can download the codec installer for these, for free, from http://xiph.org/dshow. I am planning to break down this little project into a series of blog posts, with each pattern being a single blog post over several weeks. In these I will flesh out the background behind the pattern, the basic goal being achieved and how to monitor the progress of the sample data being processed. Basically, what I said during the presentation and is missing from the slides.

    Read the article

  • C# 5 - asynch method callback with Task.ContinueWIth? [migrated]

    - by user1142433
    I have a method that pulls some HTML via the HttpClient like so: public static HttpClient web = new HttpClient(); public static async Task<string> GetHTMLDataAsync(string url) { string responseBodyAsText = ""; try { HttpResponseMessage response = await web.GetAsync(url); response.EnsureSuccessStatusCode(); responseBodyAsText = await response.Content.ReadAsStringAsync(); } catch (Exception e) { // Error handling } return responseBodyAsText; } I have another method that looks like so: private void HtmlReadComplete(string data) { // do something with the data } I would like to be able to call GetHTMLDataAsync and then have it call HtmlReadComplete on the UI thread when the html has been read. I naively thought this could somehow be done with something that looks like GetHTMLDataAsync(url).ContinueWith(HtmlReadComplete); But, I can't get the syntax correct, nor am I even sure that's the appropriate way to handle it. Thanks in advance!

    Read the article

  • F#: Tell me what I'm missing about using Async.Parallel

    - by JBristow
    ok, so I'm doing ProjectEuler Problem #14, and I'm fiddling around with optimizations in order to feel f# out. in the following code: let evenrule n = n / 2L let oddrule n = 3L * n + 1L let applyRule n = if n % 2L = 0L then evenrule n else oddrule n let runRules n = let rec loop a final = if a = 1L then final else loop (applyRule a) (final + 1L) n, loop (int64 n) 1L let testlist = seq {for i in 3 .. 2 .. 1000000 do yield i } let getAns sq = sq |> Seq.head let seqfil (a,acc) (b,curr) = if acc = curr then (a,acc) else if acc < curr then (b,curr) else (a,acc) let pmap f l = seq { for a in l do yield async {return f a} } |> Seq.map Async.RunSynchronously let pmap2 f l = seq { for a in l do yield async {return f a} } |> Async.Parallel |> Async.RunSynchronously let procseq f l = l |> f runRules |> Seq.reduce seqfil |> fst let timer = System.Diagnostics.Stopwatch() timer.Start() let ans1 = testlist |> procseq Seq.map // 837799 00:00:08.6251990 printfn "%A\t%A" ans1 timer.Elapsed timer.Reset() timer.Start() let ans2 = testlist |> procseq pmap printfn "%A\t%A" ans2 timer.Elapsed // 837799 00:00:12.3010250 timer.Reset() timer.Start() let ans3 = testlist |> procseq pmap2 printfn "%A\t%A" ans3 timer.Elapsed // 837799 00:00:58.2413990 timer.Reset() Why does the Async.Parallel code run REALLY slow in comparison to the straight up map? I know I shouldn't see that much of an effect, since I'm only on a dual core mac. Please note that I do NOT want help solving problem #14, I just want to know what's up with my parallel code.

    Read the article

  • What happens differently when you add a task Asynchronously on GAE?

    - by Ben Grunfeld
    Google's doc on async tasks assumes knowledge of the difference between regular and asynchronously added tasks. add_async(task, transactional=False, rpc=None) Asynchronously add a Task or a list of Tasks to this Queue. How is adding tasks asynchronously different to adding them regularly. I.e. what is the difference between using add(task, transactional=False) and add_async(task, transactional=False, rpc=None) I've heard that adding tasks regularly blocks certain things. Any explanation of what it blocks and how, and how async tasks don't block would be greatly appreciated.

    Read the article

  • Execute a SSIS package in Sync or Async mode from SQL Server 2012

    - by Davide Mauri
    Today I had to schedule a package stored in the shiny new SSIS Catalog store that can be enabled with SQL Server 2012. (http://msdn.microsoft.com/en-us/library/hh479588(v=SQL.110).aspx) Once your packages are stored here, they will be executed using the new stored procedures created for this purpose. This is the script that will get executed if you try to execute your packages right from management studio or through a SQL Server Agent job, will be similar to the following: Declare @execution_id bigint EXEC [SSISDB].[catalog].[create_execution] @package_name='my_package.dtsx', @execution_id=@execution_id OUTPUT, @folder_name=N'BI', @project_name=N'DWH', @use32bitruntime=False, @reference_id=Null Select @execution_id DECLARE @var0 smallint = 1 EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=50, @parameter_name=N'LOGGING_LEVEL', @parameter_value=@var0 DECLARE @var1 bit = 0 EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=50, @parameter_name=N'DUMP_ON_ERROR', @parameter_value=@var1 EXEC [SSISDB].[catalog].[start_execution] @execution_id GO The problem here is that the procedure will simply start the execution of the package and will return as soon as the package as been started…thus giving you the opportunity to execute packages asynchrously from your T-SQL code. This is just *great*, but what happens if I what to execute a package and WAIT for it to finish (and thus having a synchronous execution of it)? You have to be sure that you add the “SYNCHRONIZED” parameter to the package execution. Before the start_execution procedure: exec [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=50, @parameter_name=N'SYNCHRONIZED', @parameter_value=1 And that’s it . PS From the RC0, the SYNCHRONIZED parameter is automatically added each time you schedule a package execution through the SQL Server Agent. If you’re using an external scheduler, just keep this post in mind .

    Read the article

  • Performing a Depth First Search iteratively using async/parallel processing?

    - by Prabhu
    Here is a method that does a DFS search and returns a list of all items given a top level item id. How could I modify this to take advantage of parallel processing? Currently, the call to get the sub items is made one by one for each item in the stack. It would be nice if I could get the sub items for multiple items in the stack at the same time, and populate my return list faster. How could I do this (either using async/await or TPL, or anything else) in a thread safe manner? private async Task<IList<Item>> GetItemsAsync(string topItemId) { var items = new List<Item>(); var topItem = await GetItemAsync(topItemId); Stack<Item> stack = new Stack<Item>(); stack.Push(topItem); while (stack.Count > 0) { var item = stack.Pop(); items.Add(item); var subItems = await GetSubItemsAsync(item.SubId); foreach (var subItem in subItems) { stack.Push(subItem); } } return items; } I was thinking of something along these lines, but it's not coming together: var tasks = stack.Select(async item => { items.Add(item); var subItems = await GetSubItemsAsync(item.SubId); foreach (var subItem in subItems) { stack.Push(subItem); } }).ToList(); if (tasks.Any()) await Task.WhenAll(tasks); The language I'm using is C#.

    Read the article

  • How do you keep code with continuations/callbacks readable?

    - by Heinzi
    Summary: Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks? I'm using a JavaScript library that does a lot of stuff asynchronously and heavily relies on callbacks. It seems that writing a simple "load A, load B, ..." method becomes quite complicated and hard to follow using this pattern. Let me give a (contrived) example. Let's say I want to load a bunch of images (asynchronously) from a remote web server. In C#/async, I'd write something like this: disableStartButton(); foreach (myData in myRepository) { var result = await LoadImageAsync("http://my/server/GetImage?" + myData.Id); if (result.Success) { myData.Image = result.Data; } else { write("error loading Image " + myData.Id); return; } } write("success"); enableStartButton(); The code layout follows the "flow of events": First, the start button is disabled, then the images are loaded (await ensures that the UI stays responsive) and then the start button is enabled again. In JavaScript, using callbacks, I came up with this: disableStartButton(); var count = myRepository.length; function loadImage(i) { if (i >= count) { write("success"); enableStartButton(); return; } myData = myRepository[i]; LoadImageAsync("http://my/server/GetImage?" + myData.Id, function(success, data) { if (success) { myData.Image = data; } else { write("error loading image " + myData.Id); return; } loadImage(i+1); } ); } loadImage(0); I think the drawbacks are obvious: I had to rework the loop into a recursive call, the code that's supposed to be executed in the end is somewhere in the middle of the function, the code starting the download (loadImage(0)) is at the very bottom, and it's generally much harder to read and follow. It's ugly and I don't like it. I'm sure that I'm not the first one to encounter this problem, so my question is: Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks?

    Read the article

  • Asynchrony in C# 5 (Part II)

    - by javarg
    This article is a continuation of the series of asynchronous features included in the new Async CTP preview for next versions of C# and VB. Check out Part I for more information. So, let’s continue with TPL Dataflow: Asynchronous functions TPL Dataflow Task based asynchronous Pattern Part II: TPL Dataflow Definition (by quote of Async CTP doc): “TPL Dataflow (TDF) is a new .NET library for building concurrent applications. It promotes actor/agent-oriented designs through primitives for in-process message passing, dataflow, and pipelining. TDF builds upon the APIs and scheduling infrastructure provided by the Task Parallel Library (TPL) in .NET 4, and integrates with the language support for asynchrony provided by C#, Visual Basic, and F#.” This means: data manipulation processed asynchronously. “TPL Dataflow is focused on providing building blocks for message passing and parallelizing CPU- and I/O-intensive applications”. Data manipulation is another hot area when designing asynchronous and parallel applications: how do you sync data access in a parallel environment? how do you avoid concurrency issues? how do you notify when data is available? how do you control how much data is waiting to be consumed? etc.  Dataflow Blocks TDF provides data and action processing blocks. Imagine having preconfigured data processing pipelines to choose from, depending on the type of behavior you want. The most basic block is the BufferBlock<T>, which provides an storage for some kind of data (instances of <T>). So, let’s review data processing blocks available. Blocks a categorized into three groups: Buffering Blocks Executor Blocks Joining Blocks Think of them as electronic circuitry components :).. 1. BufferBlock<T>: it is a FIFO (First in First Out) queue. You can Post data to it and then Receive it synchronously or asynchronously. It synchronizes data consumption for only one receiver at a time (you can have many receivers but only one will actually process it). 2. BroadcastBlock<T>: same FIFO queue for messages (instances of <T>) but link the receiving event to all consumers (it makes the data available for consumption to N number of consumers). The developer can provide a function to make a copy of the data if necessary. 3. WriteOnceBlock<T>: it stores only one value and once it’s been set, it can never be replaced or overwritten again (immutable after being set). As with BroadcastBlock<T>, all consumers can obtain a copy of the value. 4. ActionBlock<TInput>: this executor block allows us to define an operation to be executed when posting data to the queue. Thus, we must pass in a delegate/lambda when creating the block. Posting data will result in an execution of the delegate for each data in the queue. You could also specify how many parallel executions to allow (degree of parallelism). 5. TransformBlock<TInput, TOutput>: this is an executor block designed to transform each input, that is way it defines an output parameter. It ensures messages are processed and delivered in order. 6. TransformManyBlock<TInput, TOutput>: similar to TransformBlock but produces one or more outputs from each input. 7. BatchBlock<T>: combines N single items into one batch item (it buffers and batches inputs). 8. JoinBlock<T1, T2, …>: it generates tuples from all inputs (it aggregates inputs). Inputs could be of any type you want (T1, T2, etc.). 9. BatchJoinBlock<T1, T2, …>: aggregates tuples of collections. It generates collections for each type of input and then creates a tuple to contain each collection (Tuple<IList<T1>, IList<T2>>). Next time I will show some examples of usage for each TDF block. * Images taken from Microsoft’s Async CTP documentation.

    Read the article

  • How can I use nested Async (WCF) calls within foreach loops in Silverlight ?

    - by Peter St Angelo
    The following code contains a few nested async calls within some foreach loops. I know the silverlight/wcf calls are called asyncrously -but how can I ensure that my wcfPhotographers, wcfCategories and wcfCategories objects are ready before the foreach loop start? I'm sure I am going about this all the wrong way -and would appreciate an help you could give. private void PopulateControl() { List<CustomPhotographer> PhotographerList = new List<CustomPhotographer>(); proxy.GetPhotographerNamesCompleted += proxy_GetPhotographerNamesCompleted; proxy.GetPhotographerNamesAsync(); //for each photographer foreach (var eachPhotographer in wcfPhotographers) { CustomPhotographer thisPhotographer = new CustomPhotographer(); thisPhotographer.PhotographerName = eachPhotographer.ContactName; thisPhotographer.PhotographerId = eachPhotographer.PhotographerID; thisPhotographer.Categories = new List<CustomCategory>(); proxy.GetCategoryNamesFilteredByPhotographerCompleted += proxy_GetCategoryNamesFilteredByPhotographerCompleted; proxy.GetCategoryNamesFilteredByPhotographerAsync(thisPhotographer.PhotographerId); // for each category foreach (var eachCatergory in wcfCategories) { CustomCategory thisCategory = new CustomCategory(); thisCategory.CategoryName = eachCatergory.CategoryName; thisCategory.CategoryId = eachCatergory.CategoryID; thisCategory.SubCategories = new List<CustomSubCategory>(); proxy.GetSubCategoryNamesFilteredByCategoryCompleted += proxy_GetSubCategoryNamesFilteredByCategoryCompleted; proxy.GetSubCategoryNamesFilteredByCategoryAsync(thisPhotographer.PhotographerId,thisCategory.CategoryId); // for each subcategory foreach(var eachSubCatergory in wcfSubCategories) { CustomSubCategory thisSubCatergory = new CustomSubCategory(); thisSubCatergory.SubCategoryName = eachSubCatergory.SubCategoryName; thisSubCatergory.SubCategoryId = eachSubCatergory.SubCategoryID; } thisPhotographer.Categories.Add(thisCategory); } PhotographerList.Add(thisPhotographer); } PhotographerNames.ItemsSource = PhotographerList; } void proxy_GetPhotographerNamesCompleted(object sender, GetPhotographerNamesCompletedEventArgs e) { wcfPhotographers = e.Result.ToList(); } void proxy_GetCategoryNamesFilteredByPhotographerCompleted(object sender, GetCategoryNamesFilteredByPhotographerCompletedEventArgs e) { wcfCategories = e.Result.ToList(); } void proxy_GetSubCategoryNamesFilteredByCategoryCompleted(object sender, GetSubCategoryNamesFilteredByCategoryCompletedEventArgs e) { wcfSubCategories = e.Result.ToList(); }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >