Search Results

Search found 1226 results on 50 pages for 'asynchronous'.

Page 18/50 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Which async call use for DB connection and still responsive GUI?--

    - by Jade
    Hi, My application connects to MSSQL but sometimes it takes a while and the GUI is getting frozen. I would like to do the connection on the other thread, I guess BeginInvoke would be the best way (I know about background worker but I would like to learn this). I have studied MSDN page but I did not understand what is the best way to use? They also say that you can use only callback when the thread that called the async.method does not need to know the results...I dont understand it as I believe I can set some variable in the other thread to "pass" the result well. I would just need the GUI to be not frozen while the connection is being established. Thank you for your advice.

    Read the article

  • Loopj Android Async Http - onFailure not fired

    - by Ashley Staggs
    I am using the great async http library from loopj, but I have run into a small snag. If the user has no internet connection or loses their connection, the app just won't return anything. This part is expected, but it also doesn't fire the onFailure method. Also, the code I have used when there is an internet connection does work so there is no problem on the server end. Here is some code that is stripped down to the minimum. It also doesn't work (I have tested this too) String url = getString(R.string.baseurl) + "/appconnect.php"; client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); client.get(url, null, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray response) { Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Throwable e, JSONArray errorResponse) { Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show(); } }); Thanks, Ashley

    Read the article

  • a script translatable to JavaScript with callback-hell automatic avoider :-)

    - by m1uan
    I looking for "translator" for JavaScript like already is CoffeScript, which will be work for example with forEach (inspired by Groovy) myArray.forEach() -> val, idx { // do something with value and idx } translate to JavaScript myArray.forEach(function(val, idx){ // do something with value and idx }); or something more usefull... function event(cb){ foo()-> err, data1; bar(data1)-> err, data2; cb(data2); } the method are encapsulated function event(cb){ foo(function(err,data1){ bar(data1, function(err, data2) { cb(data2); }); }); } I want ask if similar "compiler" to JavaScript like this even better already doesn't exists? What would be super cool... my code in nodejs looks mostly like this :-) function dealer(cb){ async.parallel([ function(pcb){ async.watterfall([function(wcb){ first(function(a){ wcb(a); }); }, function(a, wcb){ thirt(a, function(c){ wcb(c); }); fourth(a, function(d){ // dealing with “a” as well and nobody care my result }); }], function(err, array_with_ac){ pcb(array_with_ac); }); }, function(pcb){ second(function(b){ pcb(b);}); }], function(err, data){ cb(data[0][0]+data[1]+data[0][1]); // dealing with “a” “b” and “c” not with “d” }); } but, look how beautiful and readable the code could be: function dealer(cb){ first() -> a; second() -> b; third(a) -> c; // dealing with “a” fourth(a) -> d; // dealing with “a” as well and nobody care about my result cb(a+b+c); // dealing with “a” “b” and “c” not with “d” } yes this is ideal case when the translator auto-decide, method need to be run as parallel and method need be call after finish another method. I can imagine it's works Please, do you know about something similar? Thank you for any advice;-)

    Read the article

  • Problem Executing Async Web Request

    - by davidhayes
    Hi Can anyone tell me what I've done wrong with this simple code? When I run it it hangs on using (Stream postStream = request.EndGetRequestStream(asynchronousResult)) If I comment out the requestState.Wait.WaitOne(); line the code executes correctly but obviously doesn't wait for the response. I'm guessing the the call to EndGetRequestStream is somehow returning me to the context of the main thread?? I'm pretty sure my code is essentially the same as the sample though (MSDN Documentation) using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.IO; using System.Text; namespace SBRemoteClient { public class JSONClient { public string ExecuteJSONQuery(string url, string query) { System.Uri uri = new Uri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "POST"; request.Accept = "application/json"; byte[] requestBytes = Encoding.UTF8.GetBytes(query); RequestState requestState = new RequestState(request, requestBytes); IAsyncResult resultRequest = request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), requestState); requestState.Wait.WaitOne(); IAsyncResult resultResponse = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), requestState); requestState.Wait.WaitOne(); return requestState.Response; } private static void GetRequestStreamCallback(IAsyncResult asynchronousResult) { try { RequestState requestState = (RequestState)asynchronousResult.AsyncState; HttpWebRequest request = requestState.Request; using (Stream postStream = request.EndGetRequestStream(asynchronousResult)) { postStream.Write(requestState.RequestBytes, 0, requestState.RequestBytes.Length); } requestState.Wait.Set(); } catch (Exception e) { Console.Out.WriteLine(e); } } private static void GetResponseStreamCallback(IAsyncResult asynchronousResult) { RequestState requestState = (RequestState)asynchronousResult.AsyncState; HttpWebRequest request = requestState.Request; using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(responseStream)) { requestState.Response = streamRead.ReadToEnd(); requestState.Wait.Set(); } } } } } }

    Read the article

  • How do I update the UI during an event using ASP.NET?

    - by Phil Hale
    I'm a bit stuck with a problem. I feel like the solution should be fairly straight forward but I'm completely out of ideas for some reason. Here's the problem. I've got a user control with a couple of buttons. Think of them as 'On' and 'Off'. When either button is clicked an async method is called. If the method is successful an event is fired. Within the event I want to update the enabled property of the two buttons so that only a single button is clickable at any one time. The problem is that any changes I make to the properties are not shown on screen because the postback is already complete. I tried wrapping the buttons in an UpdatePanel but I get an "Update method can only be called on UpdatePanel with ID 'xxxx' before Render' error. I understand why the problem occurs but I can't think of a solution. Help! Ideally what I'd like to do is simply call a method within the event that will update the UI, but I don't know if that's possible.

    Read the article

  • How to make Django work with unsupported MySQL drivers such as gevent-mysql or Concurrence's MySQL d

    - by Continuation
    I'm interested in running Django on an async framework like Concurrence or gevent. Both frameworks come with its own async MySQL driver. Problem is Django only officially supports MySQLdb. What do I need to do to make Django work with the MySQL drivers that come with gevent or Concurrence? Is there a step-by-step guide somewhere that I can follow? Is this a major undertaking? Thanks.

    Read the article

  • Async WebRequest Timeout Windows Phone 7

    - by Tyler
    Hi All, I'm wondering what the "right" way of timing out an HttpWebRequest is on Windows Phone7? I've been reading about ThreadPool.RegisterWaitForSingleObject() but this can't be used as WaitHandles throw a Not implemented exception at run time. I've also been looking at ManualReset events but A) Don't understand them properly and B) Don't understand how blocking the calling thread is an acceptable way to implement a time out on an Async request. Here's my existing code sans timeout, can someone please show me how I would add a timeout to this? public static void Get(Uri requestUri, HttpResponseReceived httpResponseReceivedCallback, ICredentials credentials, object userState, bool getResponseAsString = true, bool getResponseAsBytes = false) { var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri); httpWebRequest.Method = "GET"; httpWebRequest.Credentials = credentials; var httpClientRequestState = new JsonHttpClientRequestState(null, userState, httpResponseReceivedCallback, httpWebRequest, getResponseAsString, getResponseAsBytes); httpWebRequest.BeginGetResponse(ResponseReceived, httpClientRequestState); } private static void ResponseReceived(IAsyncResult asyncResult) { var httpClientRequestState = asyncResult.AsyncState as JsonHttpClientRequestState; Debug.Assert(httpClientRequestState != null, "httpClientRequestState cannot be null. Fatal error."); try { var webResponse = (HttpWebResponse)httpClientRequestState.HttpWebRequest.EndGetResponse(asyncResult); } }

    Read the article

  • How to set variable before callback is called?

    - by user1995327
    I'm trying to design a webpage... I have a function that I call get all info needed for an idividuals home page. A snippet of the codes is: exports.getHomePageData = function(userId, cb) { var pageData = {}; pageData.userFullName = dbUtil.findNameByUserId(userId, function(err){ if (err) cb(err); }); pageData.classes = dbUtil.findUserClassesByUserId(userId, function(err){ if (err) cb(err); }); cb(pageData); } The problem I'm having is the cb(pageData) is being called before I even finish setting the elements. I've seen that people use the async library to solve this but I was wondering if there was any other way for me to do it without needing more modules... Thanks!

    Read the article

  • async_write/async_read problems while trying to implement question-answer logic

    - by Max
    Good day. I'm trying to implement a question - answer logic using boost::asio. On the Client I have: void Send_Message() { .... boost::asio::async_write(server_socket, boost::asio::buffer(&Message, sizeof(Message)), boost::bind(&Client::Handle_Write_Message, this, boost::asio::placeholders::error)); .... } void Handle_Write_Message(const boost::system::error_code& error) { .... std::cout << "Message was sent.\n"; .... boost::asio::async_read(server_socket_,boost::asio::buffer(&Message, sizeof(Message)), boost::bind(&Client::Handle_Read_Message, this, boost::asio::placeholders::error)); .... } void Handle_Read_Message(const boost::system::error_code& error) { .... std::cout << "I have a new message.\n"; .... } And on the Server i have the "same - logic" code: void Read_Message() { .... boost::asio::async_read(client_socket, boost::asio::buffer(&Message, sizeof(Message)), boost::bind(&Server::Handle_Read_Message, this, boost::asio::placeholders::error)); .... } void Handle_Read_Message(const boost::system::error_code& error) { .... std::cout << "I have a new message.\n"; .... boost::asio::async_write(client_socket_,boost::asio::buffer(&Message, sizeof(Message)), boost::bind(&Server::Handle_Write_Message, this, boost::asio::placeholders::error)); .... } void Handle_Write_Message(const boost::system::error_code& error) { .... std::cout << "Message was sent back.\n"; .... } Message it's just a structure. And the output on the Client is: Message was sent. Output on the Server is: I have a new message. And that's all. After this both programs are still working but nothing happens. I tried to implement code like: if (!error) { .... } else { // close sockets and etc. } But there are no errors in reading or writing. Both programs are just running normally, but doesn't interact with each other. This code is quite obvious but i can't understand why it's not working. Thanks in advance for any advice.

    Read the article

  • Real world examples of Rx

    - by theburningmonk
    I've been playing around with the Reactive Extension for a little while now, but mostly limited to handling/composing user driven events within a WPF frontend. It's such a powerful, new way of doing async programming, and I'm curious as to what other people are doing with it, and where do you think it might be able to improve the way we're currently doing things?

    Read the article

  • How to implement async pattern in windows forms application?

    - by Alkersan
    I'm using an MVC pattern in winforms application. I need to call remote service asynchronously. So On some event in View I invoke corresponding Presenter method. In Presenter I call BeginInvoke method of service. But to View must be updated only in Main Thread. I could actualy point CallBack to some function in View, and update it`s controls state, but this conflicts with MVP pattern - View must not be responsible for data it carries. This callback function must be in Presenter. But how then invoke View in Main Thread?

    Read the article

  • Handling multiple async HTTP requests in Silverlight serially

    - by Jeb
    Due to the async nature of http access via WebClient or HttpWebRequest in Silverlight 4, when I want to do multiple http get/posts serially, I find myself writing code that looks like this: doFirstGet(someParams, () => { doSecondGet(someParams, () => { doThirdGet(... } }); Or something similar. I'll end up nesting subsequent calls within callbacks usually implemented using lambdas of some sort. Even if I break things out into Actions or separate methods, it still ends up being hard to read. Does anyone have a clean solution to executing multiple http requests in SL 4 serially? I don't need things to be synchronous, I just want serial execution.

    Read the article

  • Asynch operation in WinForm app

    - by TooFat
    I have a WinForms app. that when a button is clicked retrieves a bunch of data from database formats it and displays it to the end user. The operation can take 10 - 30 seconds. I would like to display a message to the user in a Dialog just saying "Be patient the operation is running" while the operation is running and then close when the data is ready to be presented to the end user. What is the best way to do this, start a new thread, use a Delegate or something else?

    Read the article

  • nodejs async.waterfall method

    - by user1513388
    Update 2 Complete code listing var request = require('request'); var cache = require('memory-cache'); var async = require('async'); var server = '172.16.221.190' var user = 'admin' var password ='Passw0rd' var dn ='\\VE\\Policy\\Objects' var jsonpayload = {"Username": user, "Password": password} async.waterfall([ //Get the API Key function(callback){ request.post({uri: 'http://' + server +'/sdk/authorize/', json: jsonpayload, headers: {'content_type': 'application/json'} }, function (e, r, body) { callback(null, body.APIKey); }) }, //List the credential objects function(apikey, callback){ var jsonpayload2 = {"ObjectDN": dn, "Recursive": true} request.post({uri: 'http://' + server +'/sdk/Config/enumerate?apikey=' + apikey, json: jsonpayload2, headers: {'content_type': 'application/json'} }, function (e, r, body) { var dns = []; for (var i = 0; i < body.Objects.length; i++) { dns.push({'name': body.Objects[i].Name, 'dn': body.Objects[i].DN}) } callback(null, dns, apikey); }) }, function(dns, apikey, callback){ // console.log(dns) var cb = []; for (var i = 0; i < dns.length; i++) { //Retrieve the credential var jsonpayload3 = {"CredentialPath": dns[i].dn, "Pattern": null, "Recursive": false} console.log(dns[i].dn) request.post({uri: 'http://' + server +'/sdk/credentials/retrieve?apikey=' + apikey, json: jsonpayload3, headers: {'content_type': 'application/json'} }, function (e, r, body) { // console.log(body) cb.push({'cl': body.Classname}) callback(null, cb, apikey); console.log(cb) }); } } ], function (err, result) { // console.log(result) // result now equals 'done' }); Update: I'm building a small application that needs to make multiple HTTP calls to a an external API and amalgamates the results into a single object or array. e.g. Connect to endpoint and get auth key - pass auth key to step 2 Connect to endpoint using auth key and get JSON results - create an object containing summary results and pass to step 3. Iterate over passed object summary results and call API for each item in the object to get detailed information for each summary line Create a single JSON data structure that contains the summary and detail information. The original question below outlines what I've tried so far! Original Question: Will the async.waterfall method support multiple callbacks? i.e. Iterate over an array thats passed from a previous item in the chain, then invoke multiple http requests each of which would have their own callbacks. e.g, sync.waterfall([ function(dns, key, callback){ var cb = []; for (var i = 0; i < dns.length; i++) { //Retrieve the credential var jsonpayload3 = {"Cred": dns[i].DN, "Pattern": null, "Recursive": false} console.log(dns[i].DN) request.post({uri: 'http://' + vedserver +'/api/cred/retrieve?apikey=' + key, json: jsonpayload3, headers: {'content_type': 'application/json'} }, function (e, r, body) { console.log(body) cb.push({'cl': body.Classname}) callback(null, cb, key); }); } }

    Read the article

  • What happens to a transaction when App Pool recycles or the worker process is terminated forcefully?

    - by ARS
    The architecture of the application is straight forward. There is a web application which maintain account holder data. This data is processed and the status of account holders is updated based on number of business rules. This process is initiated using a button on the page and is a long running process (say 15 mins). A component is developed to do this data processing which internally calls stored procedures. Most of the business rules are kept in stored procedure. To handle timeouts the processing is done asynchornously(using Thread Pool or custom thread or Async Callback Delegates). The entire process run under a transaction. I would like to know your view on what happens to the transaction if the app pool is recycled or the worker process is terminated forcefully?

    Read the article

  • What is the best way to read files in an EventMachine-based app?

    - by Theo
    In order not to block the reactor I would like to read files asynchronously, but I've found no obvious way of doing it using EventMachine. I've tried a few different approaches, but none of them feels right: Just read the file, it'll block the reactor, but what the hell, it's not that slow (unless it's a big file, and then it definitely is). Open the file for reading and read a chunk on each tick (but how much to read? too much and it'll block the reactor, too little and reading will get slower than necessary). EM.popen('cat some/file', FileReader) feels really weird, but works better than the alternatives above. In combination with the LineAndTextProtocol it reads lines pretty swiftly. EM.attach, but I haven't found any examples of how to use it, and the only thing I've found on the mailing list is that it's deprecated in favour of… EM.watch, which I've found no examples of how to use for reading files. How do you read files within a EventMachine reactor loop?

    Read the article

  • Controller actions appear to be synchronous though on different requests?

    - by Oded
    I am under the impression that the below code should work asynchronously. However, when I am looking at firebug, I see the requests fired asynchronously, but the results coming back synchronously: Controller: [HandleError] public class HomeController : Controller { public ActionResult Status() { return Content(Session["status"].ToString()); } public ActionResult CreateSite() { Session["status"] += "Starting new site creation"; Thread.Sleep(20000); // Simulate long running task Session["status"] += "<br />New site creation complete"; return Content(string.Empty); } } Javascript/jQuery: $(document).ready(function () { $.ajax({ url: '/home/CreateSite', async: true, success: function () { mynamespace.done = true; } }); setTimeout(mynamespace.getStatus, 2000); }); var mynamespace = { counter: 0, done: false, getStatus: function () { $('#console').append('.'); if (mynamespace.counter == 4) { mynamespace.counter = 0; $.ajax({ url: '/home/Status', success: function (data) { $('#console').html(data); } }); } if (!mynamespace.done) { mynamespace.counter++; setTimeout(mynamespace.getStatus, 500); } } } Addtional information: IIS 7.0 Windows 2008 R2 Server Running in a VMWare virutual machine Can anyone explain this? Shouldn't the Status action be returning practically immediately instead of waiting for CreateSite to finish? Edit: How can I get the long running process to kick off and still get status updates?

    Read the article

  • Implement a threading to prevent UI block on a bug in an async function

    - by Marcx
    I think I ran up againt a bug in an async function... Precisely the getDirectoryListingAsync() of the File class... This method is supposted to return an object containing the lists of files in a specified folder. I found that calling this method on a direcory with a lot of files (in my tests more than 20k files), after few seconds there is a block on the UI until the process is completed... I think that this method is separated in two main block: 1) get the list of files 2) create the array with the details of the files The point 1 seems to be async (for a few second the ui is responsive), then when the process pass from point 1 to point 2 the block of the UI occurs until the complete event is dispathed... Here's some (simple) code: private function checkFiles(dir:File):void { if (dir.exists) { dir.addEventListener( FileListEvent.DIRECTORY_LISTING, listaImmaginiLocale); dir.getDirectoryListingAsync(); // after this point, for the firsts seconds the UI respond well (point 1), // few seconds later (point 2) the UI is frozen } } private function listaImmaginiLocale( event:FileListEvent ):void { // from this point on the UI is responsive again... } Actually in my projects there are some function that perform an heavy cpu usage and to prevent the UI block I implemented a simple function that after some iteration will wait giving time to UI to be refreshed. private var maxIteration:int = 150000; private function sampleFunct(offset:int = 0) :void { if (offset < maxIteration) { // do something // call the recursive function using a timeout.. // if the offset in multiple by 1000 the function will wait 15 millisec, // otherwise it will be called immediately // 1000 is a random number for the pourpose of this example, but I usually change the // value based on how much heavy is the function itself... setTimeout(function():void{aaa(++offset);}, (offset%1000?15:0)); } } Using this method I got a good responsive UI without afflicting performance... I'd like to implement it into the getDirectoryListingAsync method but I don't know if it's possibile how can I do it where is the file to edit or extend.. Any suggestion???

    Read the article

  • Async task ASP.net HttpContext.Current.Items is empty - How do handle this?

    - by GuruC
    We are running a very large web application in asp.net MVC .NET 4.0. Recently we had an audit done and the performance team says that there were a lot of null reference exceptions. So I started investigating it from the dumps and event viewer. My understanding was as follows: We are using Asyn Tasks in our controllers. We rely on HttpContext.Current.Items hashtable to store a lot of Application level values. Task<Articles>.Factory.StartNew(() => { System.Web.HttpContext.Current = ControllerContext.HttpContext.ApplicationInstance.Context; var service = new ArticlesService(page); return service.GetArticles(); }).ContinueWith(t => SetResult(t, "articles")); So we are copying the context object onto the new thread that is spawned from Task factory. This context.Items is used again in the thread wherever necessary. Say for ex: public class SomeClass { internal static int StreamID { get { if (HttpContext.Current != null) { return (int)HttpContext.Current.Items["StreamID"]; } else { return DEFAULT_STREAM_ID; } } } This runs fine as long as number of parallel requests are optimal. My questions are as follows: 1. When the load is more and there are too many parallel requests, I notice that HttpContext.Current.Items is empty. I am not able to figure out a reason for this and this causes all the null reference exceptions. 2. How do we make sure it is not null ? Any workaround if present ? NOTE: I read through in StackOverflow and people have questions like HttpContext.Current is null - but in my case it is not null and its empty. I was reading one more article where the author says that sometimes request object is terminated and it may cause problems since dispose is already called on objects. I am doing a copy of Context object - its just a shallow copy and not a deep copy.

    Read the article

  • How to tell iPhone NSURLConnection to abort

    - by Jahmic
    I have an app that makes moderate use of NSURLConnection. These async calls eventually finish and release properly (it looks like), but sometimes it takes some time for them to finish. So, there are times when I exit the app, (note, not just sending it the background), that some of these connections are still active. If I immediately restart the app, the app freezes on startup. (didFinishLaunchingWithOptions never seems to get called). While I'm not certain these connections are the issue, it would probably be good to terminate or cancel any remaining. Any suggestions on how to do this? Bonus points on how to debug the restart also. (I'm already saving NSLog statements to a downloadable file)

    Read the article

  • Async data loading with WCF service with UI capabilities

    - by Jojo
    I'm working on complex user control(with Telerik components). I'm trying to implement following functionality: Typing some text in RadTextBox(let say: "Hello.txt"). Clicking on Button "Check". onClientClick for button "Check" will call WCF method with parameters. Let say that this request/response will take more that 10 seconds, meanwhile I'll see loading image near TextBox AND the most important, I can continue to work on other fields. When WCF service responses UI will be updated with the result. Thanks in advance

    Read the article

  • API verbs for an interruptible operation

    - by 280Z28
    I have a long running task as part of my application. The task can be started, paused, resumed, and cancelled. I'm trying to find the best interface for these operations. Two seem clear: Pause and Cancel. This leaves the start and resume operations. I could include both Start and Resume. This has the downside of either requiring the API consumer to check the state before starting/resuming the operation to call the right method, or making the methods aliases of each other. I'm thinking I should include either Start or Resume, but I don't know which one is the most appropriate. Does anyone have any examples in the .NET Framework of such behavior? I prefer to follow established patterns whenever they are available.

    Read the article

  • Android: how to update UI dynamically?

    - by pandre
    I have an Android app and I need to change UI dynamically: ex: when user presses a button, I want to change the current activity's views and, as in some cases there are a lot of views involved, I need to display a ProgressDialog. I have been using an AsyncTask, but I think that it is not the best solution, because AsyncTask's doInBackground runs a different thread, so I can't update UI from there - I have to use runOnUiThread, which runs the code in the UI Thread, but freezes the progress dialog that is shown. I guess there should be more people with similar issues, as updating UI while displaying a ProgressDialog seems to be something done regularly by applications. So does anyone have a solution to this?

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >