Search Results

Search found 1486 results on 60 pages for 'winrt async'.

Page 11/60 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • ASP.Net: IHttpAsyncHandler and AsyncProcessorDelegate

    - by ctrlShiftBryan
    I have implemented an IHttpAsyncHandler. I am making about 5 different AJAX calls from a webpage that has widgets to that handler. One of those widgets takes about 15 seconds to load(because of a large database query) the others should all load in under a second. The handler is responding in a synchronous manner. I am getting very inconsistent results. The ProcessRequest method is using Session and other class level variables. Could that be causing different requests to use the same thread instead each there own? I'm getting this... Request1 --- response 1 sec Request2 --- response 14 sec Request3 --- response 14.5 sec Request4 --- response 15 sec Request5 --- response 15.5 sec but I'm looking for something more like this... Request1 --- response 1 sec Request2 --- response 14 sec Request3 --- response 1.5 sec Request4 --- response 2 sec Request5 --- response 1.5 sec Without posting too much code my implementation of the IHttpAsyncHandler methods are pretty standard. private AsyncProcessorDelegate _Delegate; protected delegate void AsyncProcessorDelegate(HttpContext context); IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { _Delegate = new AsyncProcessorDelegate(ProcessRequest); return _Delegate.BeginInvoke(context, cb, extraData); } void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) { _Delegate.EndInvoke(result); } Putting a debug break point in my IHttpAsyncHandler.BeginProcessRequest method I can see that the method isn't being fired until the last Process is complete. Also my machine.config has this entry... processModel autoConfig="true" with no other properties set. What else do I need to check for?

    Read the article

  • C# - update variable based upon results from backgroundworker

    - by Bruce
    I've got a C# program that talks to an instrument (spectrum analyzer) over a network. I need to be able to change a large number of parameters in the instrument and read them back into my program. I want to use backgroundworker to do the actual talking to the instrument so that UI performance doesn't suffer. The way this works is - 1) send command to the instrument with new parameter value, 2) read parameter back from the instrument so I can see what actually happened (for example, I try to set the center frequency above the max that the instrument will handle and it tells me what it will actually handle), and 3) update a program variable with the actual value received from the instrument. Because there are quite a few parameters to be updated I'd like to use a generic routine. The part I can't seem to get my brain around is updating the variable in my code with what comes back from the instrument via backgroundworker. If I used a separate RunWorkerCompleted event for each parameter I could hardwire the update directly to the variable. I'd like to come up with a way of using a single routine that's capable of updating any of the variables. All I can come up with is passing a reference number (different for each parameter) and using a switch statement in the RunWorkerCompleted handler to direct the result. There has to be a better way. Thanks for your help.

    Read the article

  • update variable based upon results from .NET backgroundworker

    - by Bruce
    I've got a C# program that talks to an instrument (spectrum analyzer) over a network. I need to be able to change a large number of parameters in the instrument and read them back into my program. I want to use backgroundworker to do the actual talking to the instrument so that UI performance doesn't suffer. The way this works is - 1) send command to the instrument with new parameter value, 2) read parameter back from the instrument so I can see what actually happened (for example, I try to set the center frequency above the max that the instrument will handle and it tells me what it will actually handle), and 3) update a program variable with the actual value received from the instrument. Because there are quite a few parameters to be updated I'd like to use a generic routine. The part I can't seem to get my brain around is updating the variable in my code with what comes back from the instrument via backgroundworker. If I used a separate RunWorkerCompleted event for each parameter I could hardwire the update directly to the variable. I'd like to come up with a way of using a single routine that's capable of updating any of the variables. All I can come up with is passing a reference number (different for each parameter) and using a switch statement in the RunWorkerCompleted handler to direct the result. There has to be a better way.

    Read the article

  • Calling end invoke on an asynchronous call when an exception has fired in WCF.

    - by james.ingham
    Hey, I currently have an asynchronous call with a callback, which fires this method on completion: private void TestConnectionToServerCallback(IAsyncResult iar) { bool result; try { result = testConnectionDelegate.EndInvoke(iar); Console.WriteLine("Connection made!"); } catch (EndpointNotFoundException e) { Console.WriteLine("Server Timeout. Are you connected?"); result = false; } ... } With the EndpointNotFoundException firing when the server is down or no connection can be made. My question is this, if I want to recall the testConnectionDelegate with some kind of re-try button, must I first call testConnectionDelegate.EndInvoke where the exception is caught? When I do call end invoke in the catch, I get another exception on result = testConnectionDelegate.EndInvoke(iar); whenever I call this method for the second time. This is "CommunicationObjectFaultedException". I'm assuming this is because I didn't end it properly, which is what I think I have to do. Any help would be appreciated. Thanks - James

    Read the article

  • What is stopping data flow with .NET 3.5 asynchronous System.Net.Sockets.Socket?

    - by TonyG
    I have a .NET 3.5 client/server socket interface using the asynchronous methods. The client connects to the server and the connection should remain open until the app terminates. The protocol consists of the following pattern: send stx receive ack send data1 receive ack send data2 (repeat 5-6 while more data) receive ack send etx So a single transaction with two datablocks as above would consist of 4 sends from the client. After sending etx the client simply waits for more data to send out, then begins the next transmission with stx. I do not want to break the connection between individual exchanges or after each stx/data/etx payload. Right now, after connection, the client can send the first stx, and get a single ack, but I can't put more data onto the wire after that. Neither side disconnects, the socket is still intact. The client code is seriously abbreviated as follows - I'm following the pattern commonly available in online code samples. private void SendReceive(string data) { // ... SocketAsyncEventArgs completeArgs; completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend); clientSocket.SendAsync(completeArgs); // two AutoResetEvents, one for send, one for receive if ( !AutoResetEvent.WaitAll(autoSendReceiveEvents , -1) ) Log("failed"); else Log("success"); // ... } private void OnSend( object sender , SocketAsyncEventArgs e ) { // ... Socket s = e.UserToken as Socket; byte[] receiveBuffer = new byte[ 4096 ]; e.SetBuffer(receiveBuffer , 0 , receiveBuffer.Length); e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive); s.ReceiveAsync(e); // ... } private void OnReceive( object sender , SocketAsyncEventArgs e ) {} // ... if ( e.BytesTransferred > 0 ) { Int32 bytesTransferred = e.BytesTransferred; String received = Encoding.ASCII.GetString(e.Buffer , e.Offset , bytesTransferred); dataReceived += received; } autoSendReceiveEvents[ SendOperation ].Set(); // could be moved elsewhere autoSendReceiveEvents[ ReceiveOperation ].Set(); // releases mutexes } The code on the server is very similar except that it receives first and then sends a response - the server is not doing anything (that I can tell) to modify the connection after it sends a response. The problem is that the second time I hit SendReceive in the client, the connection is already in a weird state. Do I need to do something in the client to preserve the SocketAsyncEventArgs, and re-use the same object for the lifetime of the socket/connection? I'm not sure which eventargs object should hang around during the life of the connection or a given exchange. Do I need to do something, or Not do something in the server to ensure it continues to Receive data? The server setup and response processing looks like this: void Start() { // ... listenSocket.Bind(...); listenSocket.Listen(0); StartAccept(null); // note accept as soon as we start. OK? mutex.WaitOne(); } void StartAccept(SocketAsyncEventArgs acceptEventArg) { if ( acceptEventArg == null ) { acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted); } Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg); if ( !willRaiseEvent ) ProcessAccept(acceptEventArg); // ... } private void OnAcceptCompleted( object sender , SocketAsyncEventArgs e ) { ProcessAccept(e); } private void ProcessAccept( SocketAsyncEventArgs e ) { // ... SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); readEventArgs.SetBuffer(dataBuffer , 0 , Int16.MaxValue); readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); readEventArgs.UserToken = e.AcceptSocket; dataReceived = ""; // note server is degraded for single client/thread use // As soon as the client is connected, post a receive to the connection. Boolean willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs); if ( !willRaiseEvent ) this.ProcessReceive(readEventArgs); // Accept the next connection request. this.StartAccept(e); } private void OnIOCompleted( object sender , SocketAsyncEventArgs e ) { // switch ( e.LastOperation ) case SocketAsyncOperation.Receive: ProcessReceive(e); // similar to client code // operate on dataReceived here case SocketAsyncOperation.Send: ProcessSend(e); // similar to client code } // execute this when a data has been processed into a response (ack, etc) private SendResponseToClient(string response) { // create buffer with response // currentEventArgs has class scope and is re-used currentEventArgs.SetBuffer(sendBuffer , 0 , sendBuffer.Length); Boolean willRaiseEvent = currentClient.SendAsync(currentEventArgs); if ( !willRaiseEvent ) ProcessSend(currentEventArgs); } A .NET trace shows the following when sending ABC\r\n: Socket#7588182::SendAsync() Socket#7588182::SendAsync(True#1) Data from Socket#7588182::FinishOperation(SendAsync) 00000000 : 41 42 43 0D 0A Socket#7588182::ReceiveAsync() Exiting Socket#7588182::ReceiveAsync() - True#1 And it stops there. It looks just like the first send from the client but the server shows no activity. I think that could be info overload for now but I'll be happy to provide more details as required. Thanks!

    Read the article

  • Cannot use await in Portable Class Library for Win 8 and Win Phone 8

    - by Harry Len
    I'm attempting to create a Portable Class Library in Visual Studio 2012 to be used for a Windows 8 Store app and a Windows Phone 8 app. I'm getting the following error: 'await' requires that the type 'Windows.Foundation.IAsyncOperation' have a suitable GetAwaiter method. Are you missing a using directive for 'System'? At this line of code: StorageFolder guidesInstallFolder = await Package.Current.InstalledLocation.GetFolderAsync(guidesFolder); My Portable Class Library is targeted at .NET Framework 4.5, Windows Phone 8 and .NET for Windows Store apps. I don't get this error for this line of code in a pure Windows Phone 8 project, and I don't get it in a Windows Store app either so I don't understand why it won't work in my PCL. The GetAwaiter is an extension method in the class WindowsRuntimeSystemExtensions which is in System.Runtime.WindowsRuntime.dll. Using the Object Browser I can see this dll is available in the .NET for Windows Store apps component set and in the Windows Phone 8 component set but not in the .NET Portable Subset. I just don't understand why it wouldn't be in the Portable Subset if it's available in both my targeted platforms.

    Read the article

  • How to notify client about updated UpdatePanel content on server side

    - by csh1981
    I have a problem with UpdatePanel.Update() which works initially but then stops. I have tumbled with this problem for some time and some background is needed so please read ahead. I have an ASP.net application in which I have a subpage that display computed information in graphs. Each graph is embedded in an UpdatePanel. The graph is a user control that uses the standard asp:Chart for display. My task is to enable this page with AJAX capabilities so the page is responsive during postbacks. When I access this page from another page, during the initial page rendering, I use a wait dialog for each graph and a pageload event on the client side. In the client event, a hidden button is clicked which a server event handles (the hidden button is inside an UpdatePanel so the postback is asynchronous). Each graph is computed and the UpdatePanels are in turn updated with the Chart content. This is done using UpdatePanel.Update. And it is successful. However, I also have some RadioButtons on the page. These are dynamically created. The purpose of them is to switch graph type --- to show the same data in a different way. Same type of time consuming computation is needed in order to do so. I subscribe on each RadioButton's OnCheckedChanged event and the postback is asynchronous since the radiobuttons are inside an UpdatePanel. In the server event handler I determine the type of graph and use this as an input to the Chart control. I then remove the old Chart control from my Panel and adds new Chart and then I call UpdatePanel.Update(). But with no success. Nothing happens, no errors, nothing. Why is this?? I think this is strange because if I compute every Chart data in the initial rendering instead of using the "Wait dialog"-solution described earlier then I can select graph types successfully and all subsequent AJAX requests work as intended. Also, the same code (computing the chart, removal, and adding the Chart control to Panel and UpdatePanel.Update()) is hit during the initial rendering of the page, and it works only the first time. Here is the method that computes the graph and adds it to the panel and update the UpdatePanel: public void UpdateGraph(GraphType type, GraphMapper mapper) { //Panel is the content of UpdatePanelGraph's Panel.Controls.Clear(); chart = new Chart(type, mapper); //Computation happens inside here panel.Controls.Add(chart); //UpdatePanelGraph is in UpdateMode Conditional and has //ChildrenAsTriggers set to false UpdatePanelGraph.Update(); } I really need a way for these radiobuttons to work, possible using some clientside JavaScript or another way of handling things on the server side. I have thought about using a JavaScript postback call on the UpdatePanel instead of the UpdatePanel.Update(). However, the issue I have here is how to notify the client side when the server side is finished with computing the graph? An plausible explanation of the strange behavior is also much appreciated. Any help appreciated, thanks

    Read the article

  • ASP.NET MVC 2 Cancel Asynchronous Action

    - by Sean Carpenter
    The MSDN documentation for using an asynchronous controller mentions choosing an asynchronous controller when you want to provide a way for users to cancel requests. I couldn't find any documentation related to actually allowing users to cancel asynchronous requests, however. Is there a way to indicate to ASP.Net and/or the MVC framework that a request should be canceled?

    Read the article

  • Render asp.net repeater as-and-when chunks of html is ready (streaming)

    - by sash
    The problem is to render huge reports. Basically we have lots of data that get rendered in html reports (mostly using repeater or gridview). As it so happens, the data started out small and now we have tons of it. There are lots of such reports already built so total rewrite is not an option. Heck, the business is not even letting us page the data. Now server memory is shooting up each time we try to render some reports. So the question is - is there some way we can bind data to repeater and have it stream html to browser as and when chunks are ready? That way we hope to not bring all that data into app server at once. I'm thinking we'll use a datareader or something to get parts of data and render it to browser. Any pointers, links, ideas?

    Read the article

  • What is a simple way to add a timer to a method

    - by John
    The following is in C#. I'm trying to do something very simple (I think). I have a method that loads an XML document XDocument doc = XDocument.Load(uri); , but I don't want to tie up pc resources if there are issues (connectivity, document size, etc.). So I'd like to be able to add a timeout variable that will cut the method off after a given number of seconds. I'm a newbie when it comes to asynchronous programming and find it confusing that there are so many examples written so many different ways . . . and none of them appear simple. I'd like a simple solution, if possible. Here's my thoughts so far on possible solution paths: 1) A method that wraps the existing load public XDocument LoadXDocument(string uri, int timeout){ //code } 2) A wrapper, but as an extension method XDocument doc = XDocument.LoadWithTimeout(string uri, int timeout); 3) A generic extension method. Object obj = SomeStaticClass.LoadWithTimeout(??? method, int timeout); 3), on its face seems really nice, because it would mean being able to generically add timeouts to many different method calls and not specifically tied to one type of object, but I suspect that it is either i)impossible or ii) very difficult. Please assist. Thanks.

    Read the article

  • What's wrong with consuming ConfiguredTaskAwaitable from PortableClassLibrary's class under Debugger from MSTest Runner or Console App?

    - by Stas Shusha
    *Its only Debug-time error, but a very weird one. Problem: While running with Debugger attached and calling a method, exposed in separate Portable library, returning ConfiguredTaskAwaitable, we get InvalidProgramException. Repro: Having 2 projects: PortableClassLibrary (supporting .Net 4.5; Windows Store; Windows Phone 8) with 1 class: public class Weird { public static ConfiguredTaskAwaitable GetConfiguredTaskAwaitable() { return new ConfiguredTaskAwaitable(); } } ConsoleApplication with code: static void Main(string[] args) { Weird.GetConfiguredTaskAwaitable(); } Notes: replacing ConfiguredTaskAwaitable with ConfiguredTaskAwaitable<T> (a generic version) fixes this strange issue consuming this method form WP8 or Win8 app under Debugger works fine. Currently it causes problems cause I cant run my Unit Tests under Debugger. I'm forced to change my "ObjectUnderTest" implementation to return generic ConfiguredTaskAwaitable<T>, which is fine for the real project, but still is only a workaround. The Question is: does anybody knows the reason of this error? It definitely related to Portable Class Library magic.

    Read the article

  • Can I use a single instance of a delegate to start multiple Asynchronous Requests?

    - by RobV
    Just wondered if someone could clarify the use of BeginInvoke on an instance of some delegate when you want to make multiple asynchronous calls since the MSDN documentation doesn't really cover/mention this at all. What I want to do is something like the following: MyDelegate d = new MyDelegate(this.TargetMethod); List<IAsyncResult> results = new List<IAsyncResult>(); //Start multiple asynchronous calls for (int i = 0; i < 4; i++) { results.Add(d.BeginInvoke(someParams, null, null)); } //Wait for all my calls to finish WaitHandle.WaitAll(results.Select(r => r.AsyncWaitHandle).ToArray()); //Process the Results The question is can I do this with one instance of the delegate or do I need an instance of the delegate for each individual call? Given that EndInvoke() takes an IAsyncResult as a parameter I would assume that the former is correct but I can't see anything in the documentation to indicate either way.

    Read the article

  • Intellitrace bug causes &ldquo;Operation could destabilize the runtime&rdquo; exception

    - by Magnus Karlsson
    We cant use it when we use simplemembership to handle external authorizations.   Server Error in '/' Application. Operation could destabilize the runtime. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Security.VerificationException: Operation could destabilize the runtime. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [VerificationException: Operation could destabilize the runtime.] DotNetOpenAuth.OpenId.Messages.IndirectSignedResponse.GetSignedMessageParts(Channel channel) +943 DotNetOpenAuth.OpenId.ChannelElements.ExtensionsBindingElement.GetExtensionsDictionary(IProtocolMessage message, Boolean ignoreUnsigned) +282 DotNetOpenAuth.OpenId.ChannelElements.<GetExtensions>d__a.MoveNext() +279 DotNetOpenAuth.OpenId.ChannelElements.ExtensionsBindingElement.ProcessIncomingMessage(IProtocolMessage message) +594 DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage message) +933 DotNetOpenAuth.OpenId.ChannelElements.OpenIdChannel.ProcessIncomingMessage(IProtocolMessage message) +326 DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestBase httpRequest) +1343 DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.GetResponse(HttpRequestBase httpRequestInfo) +241 DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.GetResponse() +361 DotNetOpenAuth.AspNet.Clients.OpenIdClient.VerifyAuthentication(HttpContextBase context) +136 DotNetOpenAuth.AspNet.OpenAuthSecurityManager.VerifyAuthentication(String returnUrl) +984 Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthenticationCore(HttpContextBase context, String returnUrl) +333 Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthentication(String returnUrl) +192 PrioMvcWebRole.Controllers.AccountController.ExternalLoginCallback(String returnUrl) in c:hiddenforyou lambda_method(Closure , ControllerBase , Object[] ) +127 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +250 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39 System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +87 System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +439 System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +439 System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +34 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +221 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +523 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +176 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

    Read the article

  • Thread vs async execution. What's different?

    - by Eonil
    I believed any kind of asynchronous execution makes a thread in invisible area. But if so, Async codes does not offer any performance gain than threaded codes. But I can't understand why so many developers are making many features async form. Could you explain about difference and cost of them?

    Read the article

  • how to call async method until get success response?

    - by ppp
    I am making a async method call through a delegate. Delegate pointing to a function is a void function. How can I know that the async function has been executed successfully and if not the again call that function untill I get success response. here my code- BillService bs = new BillService(); PayAdminCommisionDelegate payCom = new PayAdminCommisionDelegate(bs.PaySiteAdminByOrderNo); payCom.BeginInvoke(OrderNo,null,null);

    Read the article

  • Loading Youtube Iframe API with RequireJS

    - by davidgnin
    I'm trying to use the Youtube Iframe API inside a module definded with Require JS. As this API is loaded async and calls a function once is loaded, I used a requireJS plugin called "async", that worked before with google maps api. However, this time something isn't working. My module starts this way: define(['text!fmwk/widgets/video/video.html','fmwk/utils/browser','async!http://www.youtube.com/iframe_api'], function (videoTpl,root) { ... }); and chrome console fires this error: Uncaught Error: Load timeout for modules: async!http://www.youtube.com/iframe_api_unnormalized3,async!http://www.youtube.com/iframe_api http://requirejs.org/docs/errors.html#timeout If I don't use async plugin the object YT or its functions are undefinded, and the same happens if I download the API code. The API is loaded sometimes if I put an script tag in the head tag of the html file. All this is expected, but I don't understand because async plugin fails. Thank you for your attention and help :)

    Read the article

  • Thread Blocks During Call

    - by user578875
    I have a serious problem, I'm developing an application that mesures on call time during a call; the problem presents when, with the phone on the ear, the thread that the timer has, blocks and no longer responds before taking off my ear. The next log shows the problem. 01-11 16:14:19.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:20.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:21.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:22.597 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:23.608 14558 14566 I Estado : postDelayed Async Service 01-11 16:14:24.017 1106 1106 D iddd : select() < 0, Probably a handled signal: Interrupted system call 01-11 16:14:24.607 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:05.500 1106 1106 D iddd : select() < 0, Probably a handled signal: Interrupted system call 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service 01-11 16:18:06.026 14558 14566 I Estado : postDelayed Async Service I've been trying with Services, Timers, Threads, AyncTasks and they all present the same problem. My Code: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); HangUpService.setMainActivity(this); objHangUpService = new Intent(this, HangUpService.class); Runnable rAccion = new Runnable() { public void run() { TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); objVibrator = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE); final ListView lstLlamadas = (ListView) findViewById(R.id.lstFavoritos); final EditText txtMinutos = (EditText) findViewById(R.id.txtMinutos); final EditText txtSegundos = (EditText) findViewById(R.id.txtSegundos); ArrayList<Contacto> cContactos = new ArrayList<Contacto>(); ContactoAdapter caContactos = new ContactoAdapter(HangUp.this, R.layout.row,cContactos); Cursor curContactos = getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.TIMES_CONTACTED + " DESC"); while (curContactos.moveToNext()){ String strNombre = curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); String strID = curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts._ID)); String strHasPhone=curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); String strStarred=curContactos.getString(curContactos.getColumnIndex(ContactsContract.Contacts.STARRED)); if (Integer.parseInt(strHasPhone) > 0 && Integer.parseInt(strStarred) ==1 ) { Cursor CursorTelefono = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = " + strID, null, null); while (CursorTelefono.moveToNext()) { String strTipo=CursorTelefono.getString(CursorTelefono.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)); String strTelefono=CursorTelefono.getString(CursorTelefono.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); strNumero=strTelefono; String args[]=new String[1]; args[0]=strNumero; Cursor CursorCallLog = getContentResolver().query( android.provider.CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.NUMBER + "=?", args, android.provider.CallLog.Calls.DATE+ " DESC"); if (Integer.parseInt(strTipo)==2) { caContactos.add( new Contacto( strNombre, strTelefono ) ); } } CursorTelefono.close(); } } curContactos.close(); lstLlamadas.setAdapter(caContactos); lstLlamadas.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView a, View v, int position, long id) { Contacto mContacto=(Contacto)lstLlamadas.getItemAtPosition(position); i = new Intent(HangUp.this, Llamada.class); Log.i("Estado","Declaro Intent"); Bundle bundle = new Bundle(); bundle.putString("telefono", mContacto.getTelefono()); i.putExtras(bundle); startActivityForResult(i,SUB_ACTIVITY_ID); Log.i("Estado","Inicio Intent"); blActivo=true; try { String strMinutos=txtMinutos.getText().toString(); String strSegundos=txtSegundos.getText().toString(); if(!strMinutos.equals("") && !strSegundos.equals("")){ int Tiempo = ( (Integer.parseInt(txtMinutos.getText().toString())*60) + Integer.parseInt(txtSegundos.getText().toString()) )* 1000; handler.removeCallbacks(rVibrate); cTime = System.currentTimeMillis(); cTime=cTime+Tiempo; objHangUpAsync = new HangUpAsync(cTime,objVibrator,objPowerManager,objKeyguardLock); objHangUpAsync.execute(); objPowerManager.userActivity(Tiempo+3000, true); objHangUpService.putExtra("cTime", cTime); //startService(objHangUpService); } catch (Exception e) { e.printStackTrace(); } finally { } } }); } }; } AsyncTask: @Override protected String doInBackground(String... arg0) { blActivo = true; mWakeLock = objPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag"); objKeyguardLock.disableKeyguard(); Log.i("Estado", "Entro a doInBackground"); timer.scheduleAtFixedRate( new TimerTask() { public void run() { if (blActivo){ if (cTime blActivo=false; objVibrator.vibrate(1000); Log.i("Estado","Vibrar desde Async"); this.cancel(); }else{ try{ mWakeLock.acquire(); mWakeLock.release(); Log.i("Estado","postDelayed Async Service"); }catch(Exception e){ Log.i("Estado","Error: " + e.getMessage()); } } } } }, 0, INTERVAL); return null; }

    Read the article

  • Adding cancel ability and exception handling to async code.

    - by Rob
    I have this sample code for async operations (copied from the interwebs) public class LongRunningTask { public LongRunningTask() { //do nowt } public int FetchInt() { Thread.Sleep(2000); return 5; } } public delegate TOutput SomeMethod<TOutput>(); public class GoodPerformance { public void BeginFetchInt() { LongRunningTask lr = new LongRunningTask(); SomeMethod<int> method = new SomeMethod<int>(lr.FetchInt); // method is state object used to transfer result //of long running operation method.BeginInvoke(EndFetchInt, method); } public void EndFetchInt(IAsyncResult result) { SomeMethod<int> method = result.AsyncState as SomeMethod<int>; Value = method.EndInvoke(result); } public int Value { get; set; } } Other async approaches I tried required the aysnc page attribute, they also seemed to cancel if other page elements where actioned on (a button clicked), this approach just seemed to work. I’d like to add a cancel ability and exception handling for the longRunningTask class, but don’t erm, really know how.

    Read the article

  • How to run an async task afor every x mins in android?

    - by Shan
    how to run the async task at specific time? (I want to run it every 2 mins) I tried using post delayed but it's not working? tvData.postDelayed(new Runnable(){ @Override public void run() { readWebpage(); }}, 100); In the above code readwebpage is function which calls the async task for me.. Right now below is the method which I am using public void onCreate(Bundle savedInstanceState) { readwebapage(); } public void readWebpage() { DownloadWebPageTask task = new DownloadWebPageTask(); task.execute("http://www.google.com"); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response1 = ""; response1=read(); //read is my another function which does the real work response1=read(); super.onPostExecute(response1); return response1; } protected void onPostExecute(String result) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } TextView tvData = (TextView) findViewById(R.id.TextView01); tvData.setText(result); DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://www.google.com" }); } } This is what I my code is and it works perfectly fine but the big problem I drains my battery?

    Read the article

  • How to detect a timeout when using asynchronous Socket.BeginReceive?

    - by James Hugard
    Writing an asynchronous Ping using Raw Sockets in F#, to enable parallel requests using as few threads as possible. Not using "System.Net.NetworkInformation.Ping", because it appears to allocate one thread per request. Am also interested in using F# async workflows. The synchronous version below correctly times out when the target host does not exist/respond, but the asynchronous version hangs. Both work when the host does respond. Not sure if this is a .NET issue, or an F# one... Any ideas? (note: the process must run as Admin to allow Raw Socket access) This throws a timeout: let result = Ping.Ping ( IPAddress.Parse( "192.168.33.22" ), 1000 ) However, this hangs: let result = Ping.AsyncPing ( IPAddress.Parse( "192.168.33.22" ), 1000 ) |> Async.RunSynchronously Here's the code... module Ping open System open System.Net open System.Net.Sockets open System.Threading //---- ICMP Packet Classes type IcmpMessage (t : byte) = let mutable m_type = t let mutable m_code = 0uy let mutable m_checksum = 0us member this.Type with get() = m_type member this.Code with get() = m_code member this.Checksum = m_checksum abstract Bytes : byte array default this.Bytes with get() = [| m_type m_code byte(m_checksum) byte(m_checksum >>> 8) |] member this.GetChecksum() = let mutable sum = 0ul let bytes = this.Bytes let mutable i = 0 // Sum up uint16s while i < bytes.Length - 1 do sum <- sum + uint32(BitConverter.ToUInt16( bytes, i )) i <- i + 2 // Add in last byte, if an odd size buffer if i <> bytes.Length then sum <- sum + uint32(bytes.[i]) // Shuffle the bits sum <- (sum >>> 16) + (sum &&& 0xFFFFul) sum <- sum + (sum >>> 16) sum <- ~~~sum uint16(sum) member this.UpdateChecksum() = m_checksum <- this.GetChecksum() type InformationMessage (t : byte) = inherit IcmpMessage(t) let mutable m_identifier = 0us let mutable m_sequenceNumber = 0us member this.Identifier = m_identifier member this.SequenceNumber = m_sequenceNumber override this.Bytes with get() = Array.append (base.Bytes) [| byte(m_identifier) byte(m_identifier >>> 8) byte(m_sequenceNumber) byte(m_sequenceNumber >>> 8) |] type EchoMessage() = inherit InformationMessage( 8uy ) let mutable m_data = Array.create 32 32uy do base.UpdateChecksum() member this.Data with get() = m_data and set(d) = m_data <- d this.UpdateChecksum() override this.Bytes with get() = Array.append (base.Bytes) (this.Data) //---- Synchronous Ping let Ping (host : IPAddress, timeout : int ) = let mutable ep = new IPEndPoint( host, 0 ) let socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let mutable buffer = packet.Bytes try if socket.SendTo( buffer, ep ) <= 0 then raise (SocketException()) buffer <- Array.create (buffer.Length + 20) 0uy let mutable epr = ep :> EndPoint if socket.ReceiveFrom( buffer, &epr ) <= 0 then raise (SocketException()) finally socket.Close() buffer //---- Entensions to the F# Async class to allow up to 5 paramters (not just 3) type Async with static member FromBeginEnd(arg1,arg2,arg3,arg4,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,iar,state)), endAction, ?cancelAction=cancelAction) static member FromBeginEnd(arg1,arg2,arg3,arg4,arg5,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,arg5,iar,state)), endAction, ?cancelAction=cancelAction) //---- Extensions to the Socket class to provide async SendTo and ReceiveFrom type System.Net.Sockets.Socket with member this.AsyncSendTo( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginSendTo, this.EndSendTo ) member this.AsyncReceiveFrom( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginReceiveFrom, (fun asyncResult -> this.EndReceiveFrom(asyncResult, remoteEP) ) ) //---- Asynchronous Ping let AsyncPing (host : IPAddress, timeout : int ) = async { let ep = IPEndPoint( host, 0 ) use socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let outbuffer = packet.Bytes try let! result = socket.AsyncSendTo( outbuffer, 0, outbuffer.Length, SocketFlags.None, ep ) if result <= 0 then raise (SocketException()) let epr = ref (ep :> EndPoint) let inbuffer = Array.create (outbuffer.Length + 256) 0uy let! result = socket.AsyncReceiveFrom( inbuffer, 0, inbuffer.Length, SocketFlags.None, epr ) if result <= 0 then raise (SocketException()) return inbuffer finally socket.Close() }

    Read the article

  • Why does BeginReceiveFrom never time out?

    - by James Hugard
    I am writing an asynchronous Ping using Raw Sockets in F#, to enable parallel requests using as few threads as possible ("System.Net.NetworkInformation.Ping" appears to use one thread per request, but have not tested this... also am interested in using F# async workflows). The synchronous version below correctly times out when the target host does not exist/respond, but the asynchronous version hangs. Both work when the host does respond... Any ideas? (note: the process must run as Admin for this code to work) This throws a timeout: let result = Ping.Ping ( IPAddress.Parse( "192.168.33.22" ), 1000 ) However, this hangs: let result = Ping.PingAsync ( IPAddress.Parse( "192.168.33.22" ), 1000 ) |> Async.RunSynchronously Here's the code... module Ping open System open System.Net open System.Net.Sockets open System.Threading //---- ICMP Packet Classes type IcmpMessage (t : byte) = let mutable m_type = t let mutable m_code = 0uy let mutable m_checksum = 0us member this.Type with get() = m_type member this.Code with get() = m_code member this.Checksum = m_checksum abstract Bytes : byte array default this.Bytes with get() = [| m_type m_code byte(m_checksum) byte(m_checksum >>> 8) |] member this.GetChecksum() = let mutable sum = 0ul let bytes = this.Bytes let mutable i = 0 // Sum up uint16s while i < bytes.Length - 1 do sum <- sum + uint32(BitConverter.ToUInt16( bytes, i )) i <- i + 2 // Add in last byte, if an odd size buffer if i <> bytes.Length then sum <- sum + uint32(bytes.[i]) // Shuffle the bits sum <- (sum >>> 16) + (sum &&& 0xFFFFul) sum <- sum + (sum >>> 16) sum <- ~~~sum uint16(sum) member this.UpdateChecksum() = m_checksum <- this.GetChecksum() type InformationMessage (t : byte) = inherit IcmpMessage(t) let mutable m_identifier = 0us let mutable m_sequenceNumber = 0us member this.Identifier = m_identifier member this.SequenceNumber = m_sequenceNumber override this.Bytes with get() = Array.append (base.Bytes) [| byte(m_identifier) byte(m_identifier >>> 8) byte(m_sequenceNumber) byte(m_sequenceNumber >>> 8) |] type EchoMessage() = inherit InformationMessage( 8uy ) let mutable m_data = Array.create 32 32uy do base.UpdateChecksum() member this.Data with get() = m_data and set(d) = m_data <- d this.UpdateChecksum() override this.Bytes with get() = Array.append (base.Bytes) (this.Data) //---- Synchronous Ping let Ping (host : IPAddress, timeout : int ) = let mutable ep = new IPEndPoint( host, 0 ) let socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let mutable buffer = packet.Bytes try if socket.SendTo( buffer, ep ) <= 0 then raise (SocketException()) buffer <- Array.create (buffer.Length + 20) 0uy let mutable epr = ep :> EndPoint if socket.ReceiveFrom( buffer, &epr ) <= 0 then raise (SocketException()) finally socket.Close() buffer //---- Entensions to the F# Async class to allow up to 5 paramters (not just 3) type Async with static member FromBeginEnd(arg1,arg2,arg3,arg4,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,iar,state)), endAction, ?cancelAction=cancelAction) static member FromBeginEnd(arg1,arg2,arg3,arg4,arg5,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,arg5,iar,state)), endAction, ?cancelAction=cancelAction) //---- Extensions to the Socket class to provide async SendTo and ReceiveFrom type System.Net.Sockets.Socket with member this.AsyncSendTo( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginSendTo, this.EndSendTo ) member this.AsyncReceiveFrom( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginReceiveFrom, (fun asyncResult -> this.EndReceiveFrom(asyncResult, remoteEP) ) ) //---- Asynchronous Ping let PingAsync (host : IPAddress, timeout : int ) = async { let ep = IPEndPoint( host, 0 ) use socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let outbuffer = packet.Bytes try let! result = socket.AsyncSendTo( outbuffer, 0, outbuffer.Length, SocketFlags.None, ep ) if result <= 0 then raise (SocketException()) let epr = ref (ep :> EndPoint) let inbuffer = Array.create (outbuffer.Length + 256) 0uy let! result = socket.AsyncReceiveFrom( inbuffer, 0, inbuffer.Length, SocketFlags.None, epr ) if result <= 0 then raise (SocketException()) return inbuffer finally socket.Close() }

    Read the article

  • .NET vs Windows 8

    - by Simon Cooper
    So, day 1 of DevWeek. Lots and lots of Windows 8 and WinRT, as you would expect. The keynote had some actual content in it, fleshed out some of the details of how your apps linked into the Metro infrastructure, and confirmed that there would indeed be an enterprise version of the app store available for Metro apps.) However, that's, not what I want to focus this post on. What I do want to focus on is this: Windows 8 does not make .NET developers obsolete. Phew! .NET in the New Ecosystem In all the hype around Windows 8 the past few months, a lot of developers have got the impression that .NET has been sidelined in Windows 8; C++ and COM is back in vogue, and HTML5 + JavaScript is the New Way of writing applications. You know .NET? It's yesterday's tech. Enter the 21st Century and write <div>! However, after speaking to people at the conference, and after a couple of talks by Dave Wheeler on the innards of WinRT and how .NET interacts with it, my views on the coming operating system have changed somewhat. To summarize what I've picked up, in no particular order (none of this is official, just my sense of what's been said by various people): Metro apps do not replace desktop apps. That is, Windows 8 fully supports .NET desktop applications written for every other previous version of Windows, and will continue to do so in the forseeable future. There are some apps that simply do not fit into Metro. They do not fit into the touch-based paradigm, and never will. Traditional desktop support is not going away anytime soon. The reason Silverlight has been hidden in all the Metro hype is that Metro is essentially based on Silverlight design principles. Silverlight developers will have a much easier time writing Metro apps than desktop developers, as they would already be used to all the principles of sandboxing and separation introduced with Silverlight. It's desktop developers who are going to have to adapt how they work. .NET + XAML is equal to HTML5 + JS in importance. Although the underlying WinRT system is built on C++ & COM, most application development will be done either using .NET or HTML5. Both systems have their own wrapper around the underlying WinRT infrastructure, hiding the implementation details. The CLR is unchanged; it's still the .NET 4 CLR, running IL in .NET assemblies. The thing that changes between desktop and Metro is the class libraries, which have more in common with the Silverlight libraries than the desktop libraries. In Metro, although all the types look and behave the same to callers, some of the core BCL types are now wrappers around their WinRT equivalents. These wrappers are then enhanced using standard .NET types and code to produce the Metro .NET class libraries. You can't simply port a desktop app into Metro. The underlying file IO, network, timing and database access is either completely different or simply missing. Similarly, although the UI is programmed using XAML, the behaviour of the Metro XAML is different to WPF or Silverlight XAML. Furthermore, the new design principles and touch-based interface for Metro applications demand a completely new UI. You will be able to re-use sections of your app encapsulating pure program logic, but everything else will need to be written from scratch. Microsoft has taken the opportunity to remove a whole raft of types and methods from the Metro framework that are obsolete (non-generic collections) or break the sandbox (synchronous APIs); if you use these, you will have to rewrite to use the alternatives, if they exist at all, to move your apps to Metro. If you want to write public WinRT components in .NET, there are some quite strict rules you have to adhere to. But the compilers know about these rules; you can write them in C# or VB, and the compilers will tell you when you do something that isn't allowed and deal with the translation to WinRT metadata rather than .NET assemblies. It is possible to write a class library that can be used in Metro and desktop applications. However, you need to be very careful not to use types that are available in one but not the other. One can imagine developers writing their own abstraction around file IO and UIs (MVVM anyone?) that can be implemented differently in Metro and desktop, but look the same within your shared library. So, if you're a .NET developer, you have a lot less to worry about. .NET is a viable platform on Metro, and traditional desktop apps are not going away. You don't have to learn HTML5 and JavaScript if you don't want to. Hurray!

    Read the article

  • Is there a way to unit test an async method?

    - by Jiho Han
    I am using Xunit and NMock on .NET platform. I am testing a presentation model where a method is asynchronous. The method creates an async task and executes it so the method returns immediately and the state I need to check aren't ready yet. I can set a flag upon finish without modifying the SUT but that would mean I would have to keep checking the flag in a while loop for example, with perhaps timeout. What are my options?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >