Search Results

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

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

  • Does async and await incease performance of an ASP.Net application

    - by Kerezo
    I recently read a article about c#-5 and new $ nice asynchronous programming. I see it works greate in windows application. The question came to me before is if this feature can increase ASP.Net performance? consider this code: public T GetData() { var d = GetSomeData(); return d; } and public async T GetData2() { var d = await GetSomeData(); return d; } Has in an ASP.Net appication that two codes difference? thanks

    Read the article

  • Asynchrony in C# 5 (Part I)

    - by javarg
    I’ve been playing around with the new Async CTP preview available for download from Microsoft. It’s amazing how language trends are influencing the evolution of Microsoft’s developing platform. Much effort is being done at language level today than previous versions of .NET. In these post series I’ll review some major features contained in this release: Asynchronous functions TPL Dataflow Task based asynchronous Pattern Part I: Asynchronous Functions This is a mean of expressing asynchronous operations. This kind of functions must return void or Task/Task<> (functions returning void let us implement Fire & Forget asynchronous operations). The two new keywords introduced are async and await. async: marks a function as asynchronous, indicating that some part of its execution may take place some time later (after the method call has returned). Thus, all async functions must include some kind of asynchronous operations. This keyword on its own does not make a function asynchronous thought, its nature depends on its implementation. await: allows us to define operations inside a function that will be awaited for continuation (more on this later). Async function sample: Async/Await Sample async void ShowDateTimeAsync() {     while (true)     {         var client = new ServiceReference1.Service1Client();         var dt = await client.GetDateTimeTaskAsync();         Console.WriteLine("Current DateTime is: {0}", dt);         await TaskEx.Delay(1000);     } } The previous sample is a typical usage scenario for these new features. Suppose we query some external Web Service to get data (in this case the current DateTime) and we do so at regular intervals in order to refresh user’s UI. Note the async and await functions working together. The ShowDateTimeAsync method indicate its asynchronous nature to the caller using the keyword async (that it may complete after returning control to its caller). The await keyword indicates the flow control of the method will continue executing asynchronously after client.GetDateTimeTaskAsync returns. The latter is the most important thing to understand about the behavior of this method and how this actually works. The flow control of the method will be reconstructed after any asynchronous operation completes (specified with the keyword await). This reconstruction of flow control is the real magic behind the scene and it is done by C#/VB compilers. Note how we didn’t use any of the regular existing async patterns and we’ve defined the method very much like a synchronous one. Now, compare the following code snippet  in contrast to the previuous async/await: Traditional UI Async void ComplicatedShowDateTime() {     var client = new ServiceReference1.Service1Client();     client.GetDateTimeCompleted += (s, e) =>     {         Console.WriteLine("Current DateTime is: {0}", e.Result);         client.GetDateTimeAsync();     };     client.GetDateTimeAsync(); } The previous implementation is somehow similar to the first shown, but more complicated. Note how the while loop is implemented as a chained callback to the same method (client.GetDateTimeAsync) inside the event handler (please, do not do this in your own application, this is just an example).  How it works? Using an state workflow (or jump table actually), the compiler expands our code and create the necessary steps to execute it, resuming pending operations after any asynchronous one. The intention of the new Async/Await pattern is to let us think and code as we normally do when designing and algorithm. It also allows us to preserve the logical flow control of the program (without using any tricky coding patterns to accomplish this). The compiler will then create the necessary workflow to execute operations as the happen in time.

    Read the article

  • Making Ninject Interceptors work with async methods

    - by captncraig
    I am starting to work with ninject interceptors to wrap some of my async code with various behaviors and am having some trouble getting everything working. Here is an interceptor I am working with: public class MyInterceptor : IInterceptor { public async void Intercept(IInvocation invocation) { try { invocation.Proceed(); //check that method indeed returns Task await (Task) invocation.ReturnValue; RecordSuccess(); } catch (Exception) { RecordError(); invocation.ReturnValue = _defaultValue; throw; } } This appears to run properly in most normal cases. I am not sure if this will do what I expect. Although it appears to return control flow to the caller asynchronously, I am still a bit worried about the possibility that the proxy is unintentionally blocking a thread or something. That aside, I cannot get the exception handling working. For this test case: [Test] public void ExceptionThrown() { try { var interceptor = new MyInterceptor(DefaultValue); var invocation = new Mock<IInvocation>(); invocation.Setup(x => x.Proceed()).Throws<InvalidOperationException>(); interceptor.Intercept(invocation.Object); } catch (Exception e) { } } I can see in the interceptor that the catch block is hit, but the catch block in my test is never hit from the rethrow. I am more confused because there is no proxy or anything here, just pretty simple mocks and objects. I also tried something like Task.Run(() => interceptor.Intercept(invocation.Object)).Wait(); in my test, and still no change. The test passes happily, but the nUnit output does have the exception message. I imagine I am messing something up, and I don't quite understand what is going on as much as I think I do. Is there a better way to intercept an async method? What am I doing wrong with regards to exception handling?

    Read the article

  • What's the best practice for async APIs that return futures on Scala?

    - by Maurício Linhares
    I have started a project to write an async PostgreSQL driver on Scala and to be async, I need to accept callbacks and use futures, but then accepting a callback and a future makes the code cumbersome because you always have to send a callback even if it is useless. Here's a test: "insert a row in the database" in { withHandler { (handler, future) => future.get(5, TimeUnit.SECONDS) handler.sendQuery( this.create ){ query => }.get( 5, TimeUnit.SECONDS ) handler.sendQuery( this.insert ){ query => }.get( 5, TimeUnit.SECONDS ).rowsAffected === 1 } } Sending the empty callback is horrible but I couldn't find a way to make it optional or anything like that, so right now I don't have a lot of ideas on how this external API should look like. It could be something like: handler.sendQuery( this.create ).addListener { query => println(query) } But then again, I'm not sure how people are organizing API's in this regard. Providing examples in other projects would also be great.

    Read the article

  • The .NET 4.5 async/await Commands in Promise and Practice

    The .NET 4.5 async/await feature provides an opportunity for improving the scalability and performance of applications, particularly where tasks are more effectively done in parallel. The question is: do the scalability gains come at a cost of slowing individual methods? In this article Jon Smith investigates this issue by conducting a side-by-side evaluation of the standard synchronous methods and the new async methods in real applications.

    Read the article

  • How to perform 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; } EDIT: 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); UPDATE: If I wanted to chunk the tasks, would something like this work? foreach (var batch in items.BatchesOf(100)) { var tasks = batch.Select(async item => { await DoSomething(item); }).ToList(); if (tasks.Any()) { await Task.WhenAll(tasks); } } The language I'm using is C#.

    Read the article

  • Async Call To Services

    - by Pita.O
    Hi Is there any time it would not be a good idea to call web services async? My data layer is a REST-based interface and I thinking of adopting an async-only approach to all the CRUD in the system. Is there anything I should know?

    Read the article

  • Problem in working with async and await?

    - by Vicky
    I am trying to upload files to Azure Blob Storage and after successful upload adding the filename to a list for my further operation. When i am doing synchronous it works fine but when i am doing async the error occured. Error : Collection was modified; enumeration operation may not execute. foreach(var file in files) { // ..... await blockBlob.UploadFromStreamAsync(fs); listOfMovedLabelFiles.Add(fileName); } if (listOfMovedLabelFiles.Count > 0) // error point { // my code for further operation } Is there any way to wait till all the async operations get completed.

    Read the article

  • C# async and actors

    - by Alex.Davies
    If you read my last post about async, you might be wondering what drove me to write such odd code in the first place. The short answer is that .NET Demon is written using NAct Actors. Actors are an old idea, which I believe deserve a renaissance under C# 5. The idea is to isolate each stateful object so that only one thread has access to its state at any point in time. That much should be familiar, it's equivalent to traditional lock-based synchronization. The different part is that actors pass "messages" to each other rather than calling a method and waiting for it to return. By doing that, each thread can only ever be holding one lock. This completely eliminates deadlocks, my least favourite concurrency problem. Most people who use actors take this quite literally, and there are plenty of frameworks which help you to create message classes and loops which can receive the messages, inspect what type of message they are, and process them accordingly. But I write C# for a reason. Do I really have to choose between using actors and everything I love about object orientation in C#? Type safety Interfaces Inheritance Generics As it turns out, no. You don't need to choose between messages and method calls. A method call makes a perfectly good message, as long as you don't wait for it to return. This is where asynchonous methods come in. I have used NAct for a while to wrap my objects in a proxy layer. As long as I followed the rule that methods must always return void, NAct queued up the call for later, and immediately released my thread. When I needed to get information out of other actors, I could use EventHandlers and callbacks (continuation passing style, for any CS geeks reading), and NAct would call me back in my isolated thread without blocking the actor that raised the event. Using callbacks looks horrible though. To remind you: m_BuildControl.FilterEnabledForBuilding(    projects,    enabledProjects = m_OutOfDateProjectFinder.FilterNeedsBuilding(        enabledProjects,             newDirtyProjects =             {                 ....... Which is why I'm really happy that NAct now supports async methods. Now, methods are allowed to return Task rather than just void. I can await those methods, and C# 5 will turn the rest of my method into a continuation for me. NAct will run the other method in the other actor's context, but will make sure that when my method resumes, we're back in my context. Neither actor was ever blocked waiting for the other one. Apart from when they were actually busy doing something, they were responsive to concurrent messages from other sources. To be fair, you could use async methods with lock statements to achieve exactly the same thing, but it's ugly. Here's a realistic example of an object that has a queue of data that gets passed to another object to be processed: class QueueProcessor {    private readonly ItemProcessor m_ItemProcessor = ...     private readonly object m_Sync = new object();    private Queue<object> m_DataQueue = ...    private List<object> m_Results = ...     public async Task ProcessOne() {         object data = null;         lock (m_Sync)         {             data = m_DataQueue.Dequeue();         }         var processedData = await m_ItemProcessor.ProcessData(data); lock (m_Sync)         {             m_Results.Add(processedData);         }     } } We needed to write two lock blocks, one to get the data to process, one to store the result. The worrying part is how easily we could have forgotten one of the locks. Compare that to the version using NAct: class QueueProcessorActor : IActor { private readonly ItemProcessor m_ItemProcessor = ... private Queue<object> m_DataQueue = ... private List<object> m_Results = ... public async Task ProcessOne()     {         // We are an actor, it's always thread-safe to access our private fields         var data = m_DataQueue.Dequeue();         var processedData = await m_ItemProcessor.ProcessData(data);         m_Results.Add(processedData);     } } You don't have to explicitly lock anywhere, NAct ensures that your code will only ever run on one thread, because it's an actor. Either way, async is definitely better than traditional synchronous code. Here's a diagram of what a typical synchronous implementation might do: The left side shows what is running on the thread that has the lock required to access the QueueProcessor's data. The red section is where that lock is held, but doesn't need to be. Contrast that with the async version we wrote above: Here, the lock is released in the middle. The QueueProcessor is free to do something else. Most importantly, even if the ItemProcessor sometimes calls the QueueProcessor, they can never deadlock waiting for each other. So I thoroughly recommend you use async for all code that has to wait a while for things. And if you find yourself writing lots of lock statements, think about using actors as well. Using actors and async together really takes the misery out of concurrent programming.

    Read the article

  • Asynch a synchronous method with await async

    - by Sahil Malik
    SharePoint, WCF and Azure Trainings: more information Stock this in “bag of tricks”, but very frequently we run into APIs that do not offer Asynch methods.But between C# ‘s amazing set of features, and asynch await keywords, there is a lot you can do. For instance, consider this code - Read full article ....

    Read the article

  • jsTree: async loading

    - by vandalo
    Hello everyone, I am trying to use this jQuery plugin (jsTree) in one of my project. All the others I've found haven't been recently updated. Anyway, I am using this plugin to load a folder structure, but I would like to do this operation async. The examples I've found on their site (called async) are ridiculous. I've tried to check on the Internet but it seems that most people load the whole tree. I would like to load a branch on every single node click. I am using JSON. Thank in advance

    Read the article

  • Is it possible to port a Windows RT app to a Windows Phone app?

    - by balint
    Just recently released an application to the Windows Store, and I'm wondering if it is possible to "downgrade" it to Windows Phone 7.1 - until Windows Phone 8 will arrive. The real problem is with the async stuff, I've found the "Async Targeting Pack", but it requires Visual Studio 2012; however VS2012 doesn't work with the Phone SDK 7.0, 7.1. I'm not in the mood to install old and ugly Visual Studio 2010 on my brand new Windows 8 machine :) Does anyone know a workaround?

    Read the article

  • jQuery-ajax call: async property is not working?

    - by user269386
    Hi, given to certain circumstances, I'm forced to keep page settings (Javascript-values) in the session and it has to be done right before leaving the page (I can't use cookies, since "pageSettings" can become quite large and localStorage is not an option yet ;) ). So this is how I tried it. However it seems that when I call the page directly again, the call of "http://blabla.com/bla" happens asynchronous, even though the async-attribute is set (I don't receive the settings of the previous call, but of the one before): $jQ(document).ready(function () { $jQ(window).unload(Main.__setSessionValues); }); var Main = { pageSettings: {}, __setSessionValues: function __setSessionValues() { $jQ.ajax({ type: "POST", async: false, url: "http://blabla.com/bla", data: { pageSettings: Object.toJSON(Main.pageSettings) } }); } }; Does anyone know what the problem might be? thanks in advance

    Read the article

  • Strange WPF Behaviour With WCF Async calls

    - by gvigsgb
    I have a WPF application calling WCF via Async calls. The application has four tabs in which each are loaded from seperate async calls, each tab has a busy indicator. The problem: When running within Visual Studio I can click a refresh button on each tab and each tab's busy indicator starts and the data is retrieved from the WCF service. As each tab's data comes back it is refreshed. When I deploy the application via one click the application's UI hangs after only two tabs start refreshing. So in this case I press refresh on tab one, then on tab two and the application hangs until one of the two tabs data comes back. I thought at first that it was something to do with the WCF service throtteling and that was not the case as both the Visual Studio and the One Click deployments of the application point to the same service. Anyone have any ideas on where to look? I cannot reproduce the hang issue within Visual Studio?

    Read the article

  • Async & Await in C# with Xamarin

    - by Wallym
     One of the great things about the .NET Framework is that Microsoft has worked long and hard to improve many features. Since the initial release of .NET 1.0, there has been support for threading via .NET threads as well as an application-level threadpool. This provided a great starting point when compared to Visual Basic 6 and classic ASP programming. The release of.NET 4 brought significant improvements in the area of threading, asynchronous operations and parallel operations. While the improvements made working with asynchronous operations easier, new problems were introduced, since many of these operations work based on callbacks. For example: How should a developer handle error checking? The program flow tends to be non-linear. Fixing bugs can be problematic. It is hard for a developer to get an understanding of what is happening within an application. The release of .NET 4.5 (and C# 5.0), in the fall of 2012, was a blockbuster update with regards to asynchronous operations and threads. Microsoft has added C# language keywords to take this non-linear callback-based program flow and turn it into a much more linear flow. Recently, Xamarin has updated Xamarin.Android and Xamarin.iOS to support async. This article will look at how Xamarin has implemented the .NET 4.5/C# 5 support into their Xamarin.iOS and Xamarin.Android productions. There are three general areas that I'll focus on: A general look at the asynchronous support in Xamarin's mobile products. This includes async, await, and the implications that this has for cross-platform code. The new HttpClient class that is provided in .NET 4.5/Mono 3.2. Xamarin's extensions for asynchronous operations for Android and iOS. FYI: Be aware that sometimes the OpenWeatherMap API breaks, for no reason.  I found this out after I shipped the article in.

    Read the article

  • AsyncBridge? Async on .NET 4.0 using VS11

    - by Alex.Davies
    I've just found something quite cool. It's a code snippet that lets you use the real VS 11 C#5 compiler to write code that uses the async and await keywords, but to target .NET 4.0. It was published by Daniel Grunwald (from SharpDevelop).That means I can stop using the Async CTP for VS2010, which is not at all supported anymore, and a pain to install if you have windows updates turned on. Obviously I couldn't ask all my users to install .NET 4.5 beta, but .NET Demon is a VS 2010 extension, so we already have .NET 4.0. At the time of writing, VS11 is in beta still, but hopefully it's stable enough for my team to use!I would have written the code myself, but I had the wrong impression that the C# 5 beta compiler only looked in mscorlib for the helper classes it needs to implement async methods. Turns out you can provide them yourself. You can get the code here: https://gist.github.com/1961087You just add it to your project, and the compiler will apparently pick it up and use it to implement async/await. I'm at my parents' place for Easter without access to a machine with VS 11 to try it out. Let me know whether you get it to work!This reminds me of LINQBridge, which let us use C# 3 LINQ, but only require .NET 2. We should stick up a webpage to explain, with a nice easy dll, put it in nuget, and call it AsyncBridge.If you were really enthusiastic, you could re-implement the skeleton of the Task Parallel Library against .NET 2 to use async/await without even requiring .NET 4. Our usage stats suggest that practically everyone that uses Red Gate tools already has .NET 4 installed though, so I don't think I'll go to the effort.

    Read the article

  • jsTree async with preloaded data.

    - by Paul Knopf
    I am trying to make a tree view be async. When the page is rendered, there is default tree items displayed. jsTree tries to reload the root anyway. I want the page to render (with jsTree init'ed) with default items rendered from browser, not the ajax call. Then we the user tries to go deeper, thats when I want to do do the ajax calls. Any help is appreciated. Thanks!

    Read the article

  • python gio waiting for async operations to be done

    - by pygabriel
    I have to mount a WebDav location and wait for the operation to be finished before to proceed (it's a script). So I'm using the library in this way: location = gio.File("dav://server.bb") location.mount_enclosing_volume(*args,**kw) # The setup is not much relevant location.get_path() # Returns None because it's not yet mounted since the call is async How to wait until the device is mounted?

    Read the article

  • Async actions inside Silverlight Method - returning the value

    - by tyndall
    What is the proper way to call an Async framework component - wait for an answer and then return the value. AKA contain the entire request/response in a single method. Example code: public class Experiment { public Experiment() { } public string GetSomeString() { WebClient wc = new WebClient(); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); Uri u = new Uri("http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=t&output=rss"); wc.DownloadStringAsync(u); return "the news RSS from Google"; } private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //don't really see how this callback method makes it able // to return the answer I'm looking for on the return // statement in the method above. } } MORE INFO: The reason I'm asking this that I have a project I'm working on where I'd like JavaScript code in the browser to use Silverlight like a Facade/Proxy to Web services and complex calculations & operations. I'd like to make the calls to the [ScriptableMembers] in Silvelight synchronously. I don't want Silverlight to callback into the browser's JavaScript

    Read the article

  • 'Loading' web page for async call

    - by Sieg
    I have a simple web page in ASP.NET / C#. Currently to fully render the data I require calling a block of code that runs on background threads and can take multiple minutes to complete. I've got it to the point (using the async attribute on the page declaration) to execute and return fine with the html once it's done. What I'd like it to do is allow me to return immediately with a 'loading page' of some sort and then have that page be updated when the background work has been completed. Right now I get nothing on the page while the background work is being processed. Any ideas on the best way or clever way to do that would greatly be appreciated! Thanks, Sieg

    Read the article

  • How can I await the first completed async task of a list in .Net?

    - by Eyal
    My input is a long list of files located on an Amazon S3 server. I'd like to download the metadata of the files, compute the hashes of the local files, and compare the metadata hash with the local files' hash. Currently, I use a loop to start all the metadata downloads asynchronously, then as each completes, compute MD5 on the local file if needed and compare. Here's the code (just the relevant lines): Dim s3client As New AmazonS3Client(KeyId.Text, keySecret.Text) Dim responseTasks As New List(Of System.Tuple(Of ListViewItem, Task(Of GetObjectMetadataResponse))) For Each lvi As ListViewItem In lvStatus.Items Dim gomr As New Amazon.S3.Model.GetObjectMetadataRequest gomr.BucketName = S3FileDialog.GetBucketName(lvi.SubItems(2).Text) gomr.Key = S3FileDialog.GetPrefix(lvi.SubItems(2).Text) responseTasks.Add(New System.Tuple(Of ListViewItem, Task(Of GetObjectMetadataResponse))(lvi, s3client.GetObjectMetadataAsync(gomr))) Next For Each t As System.Tuple(Of ListViewItem, Task(Of GetObjectMetadataResponse)) In responseTasks Dim response As GetObjectMetadataResponse = Await t.Item2 If response.ETag.Trim(""""c) = MD5CalcFile(lvi.SubItems(1).Text) Then lvi.SubItems(3).Text = "Match" UpdateLvi(lvi) End If Next I've got two problems: I'm awaiting the reponses in the order that I made them. I'd rather process them in the order that they complete so that I get them faster. The MD5 calculation is long and synchronous. I tried making it async but the process locked up. I think that the MD5 task was added to the end of .Net's task list and it didn't get to run until all the downloads completed. Ideally, I process the response as they arrive, not in order, and the MD5 is asynchronous but gets a chance to run. Edit: Incorporating WhenAll, it looks like this now: Dim s3client As New Amazon.S3.AmazonS3Client(KeyId.Text, keySecret.Text) Dim responseTasks As New Dictionary(Of Task(Of GetObjectMetadataResponse), ListViewItem) For Each lvi As ListViewItem In lvStatus.Items Dim gomr As New Amazon.S3.Model.GetObjectMetadataRequest gomr.BucketName = S3FileDialog.GetBucketName(lvi.SubItems(2).Text) gomr.Key = S3FileDialog.GetPrefix(lvi.SubItems(2).Text) responseTasks.Add(s3client.GetObjectMetadataAsync(gomr), lvi) Next Dim startTime As DateTimeOffset = DateTimeOffset.Now Do While responseTasks.Count > 0 Dim currentTask As Task(Of GetObjectMetadataResponse) = Await Task.WhenAny(responseTasks.Keys) Dim response As GetObjectMetadataResponse = Await currentTask If response.ETag.Trim(""""c) = MD5CalcFile(lvi.SubItems(1).Text) Then lvi.SubItems(3).Text = "Match" UpdateLvi(lvi) End If Loop MsgBox((DateTimeOffset.Now - startTime).ToString) The UI locks up momentarily whenever MDSCalcFile is done. The whole loop takes about 45s and the first file's MD5 result happens within 1s of starting. If I change the line to: If response.ETag.Trim(""""c) = Await Task.Run(Function () MD5CalcFile(lvi.SubItems(1).Text)) Then The UI doesn't lock up when MD5CalcFile is done. The whole loop takes about 75s, up from 45s, and the first file's MD5 result happens after 40s of waiting.

    Read the article

  • Async Load JavaScript Files with Callback

    - by Gcoop
    Hi All, I am trying to write an ultra simple solution to load a bunch of JS files asynchronously. I have the following script below so far. However the callback is sometimes called when the scripts aren't actually loaded which causes a variable not found error. If I refresh the page sometimes it just works because I guess the files are coming straight from the cache and thus are there quicker than the callback is called, it's very strange? var Loader = function () { } Loader.prototype = { require: function (scripts, callback) { this.loadCount = 0; this.totalRequired = scripts.length; this.callback = callback; for (var i = 0; i < scripts.length; i++) { this.writeScript(scripts[i]); } }, loaded: function (evt) { this.loadCount++; if (this.loadCount == this.totalRequired && typeof this.callback == 'function') this.callback.call(); }, writeScript: function (src) { var self = this; var s = document.createElement('script'); s.type = "text/javascript"; s.async = true; s.src = src; s.addEventListener('load', function (e) { self.loaded(e); }, false); var head = document.getElementsByTagName('head')[0]; head.appendChild(s); } } Is there anyway to test that a JS file is completely loaded, without putting something in the actual JS file it's self, because I would like to use the same pattern to load libraries out of my control (GMaps etc). Invoking code, just before the tag. var l = new Loader(); l.require([ "ext2.js", "ext1.js"], function() { var config = new MSW.Config(); Refraction.Application().run(MSW.ViewMapper, config); console.log('All Scripts Loaded'); }); Thanks for any help.

    Read the article

  • C# Accepting sockets in async fasion - best practices

    - by psulek
    What is the best way to accept new sockets in async way. First way: while (!abort && listener.Server.IsBound) { acceptedSocketEvent.Reset(); listener.BeginAcceptSocket(AcceptConnection, null); bool signaled = false; do { signaled = acceptedSocketEvent.WaitOne(1000, false); } while (!signaled && !abort && listener.Server.IsBound); } where AcceptConnection should be: private void AcceptConnection(IAsyncResult ar) { // Signal the main thread to continue. acceptedSocketEvent.Set(); Socket socket = listener.EndAcceptSocket(ar); // continue to receive data and so on... .... } or Second way: listener.BeginAcceptSocket(AcceptConnection, null); while (!abort && listener.Server.IsBound) { Thread.Sleep(500); } and AcceptConnection will be: private void AcceptConnection(IAsyncResult ar) { Socket socket = listener.EndAcceptSocket(ar); // begin accepting next socket listener.BeginAcceptSocket(AcceptConnection, null); // continue to receive data and so on... .... } What is your prefered way and why?

    Read the article

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