Search Results

Search found 114 results on 5 pages for 'asynccallback'.

Page 3/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • .Net 3.5 Asynchronous Socket Server Performance Problem

    - by iBrAaAa
    I'm developing an Asynchronous Game Server using .Net Socket Asynchronous Model( BeginAccept/EndAccept...etc.) The problem I'm facing is described like that: When I have only one client connected, the server response time is very fast but once a second client connects, the server response time increases too much. I've measured the time from a client sends a message to the server until it gets the reply in both cases. I found that the average time in case of one client is about 17ms and in case of 2 clients about 280ms!!! What I really see is that: When 2 clients are connected and only one of them is moving(i.e. requesting service from the server) it is equivalently equal to the case when only one client is connected(i.e. fast response). However, when the 2 clients move at the same time(i.e. requests service from the server at the same time) their motion becomes very slow (as if the server replies each one of them in order i.e. not simultaneously). Basically, what I am doing is that: When a client requests a permission for motion from the server and the server grants him the request, the server then broadcasts the new position of the client to all the players. So if two clients are moving in the same time, the server is eventually trying to broadcast to both clients the new position of each of them at the same time. EX: Client1 asks to go to position (2,2) Client2 asks to go to position (5,5) Server sends to each of Client1 & Client2 the same two messages: message1: "Client1 at (2,2)" message2: "Client2 at (5,5)" I believe that the problem comes from the fact that Socket class is thread safe according MSDN documentation http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx. (NOT SURE THAT IT IS THE PROBLEM) Below is the code for the server: /// /// This class is responsible for handling packet receiving and sending /// public class NetworkManager { /// /// An integer to hold the server port number to be used for the connections. Its default value is 5000. /// private readonly int port = 5000; /// /// hashtable contain all the clients connected to the server. /// key: player Id /// value: socket /// private readonly Hashtable connectedClients = new Hashtable(); /// /// An event to hold the thread to wait for a new client /// private readonly ManualResetEvent resetEvent = new ManualResetEvent(false); /// /// keeps track of the number of the connected clients /// private int clientCount; /// /// The socket of the server at which the clients connect /// private readonly Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); /// /// The socket exception that informs that a client is disconnected /// private const int ClientDisconnectedErrorCode = 10054; /// /// The only instance of this class. /// private static readonly NetworkManager networkManagerInstance = new NetworkManager(); /// /// A delegate for the new client connected event. /// /// the sender object /// the event args public delegate void NewClientConnected(Object sender, SystemEventArgs e); /// /// A delegate for the position update message reception. /// /// the sender object /// the event args public delegate void PositionUpdateMessageRecieved(Object sender, PositionUpdateEventArgs e); /// /// The event which fires when a client sends a position message /// public PositionUpdateMessageRecieved PositionUpdateMessageEvent { get; set; } /// /// keeps track of the number of the connected clients /// public int ClientCount { get { return clientCount; } } /// /// A getter for this class instance. /// /// only instance. public static NetworkManager NetworkManagerInstance { get { return networkManagerInstance; } } private NetworkManager() {} /// Starts the game server and holds this thread alive /// public void StartServer() { //Bind the mainSocket to the server IP address and port mainSocket.Bind(new IPEndPoint(IPAddress.Any, port)); //The server starts to listen on the binded socket with max connection queue //1024 mainSocket.Listen(1024); //Start accepting clients asynchronously mainSocket.BeginAccept(OnClientConnected, null); //Wait until there is a client wants to connect resetEvent.WaitOne(); } /// /// Receives connections of new clients and fire the NewClientConnected event /// private void OnClientConnected(IAsyncResult asyncResult) { Interlocked.Increment(ref clientCount); ClientInfo newClient = new ClientInfo { WorkerSocket = mainSocket.EndAccept(asyncResult), PlayerId = clientCount }; //Add the new client to the hashtable and increment the number of clients connectedClients.Add(newClient.PlayerId, newClient); //fire the new client event informing that a new client is connected to the server if (NewClientEvent != null) { NewClientEvent(this, System.EventArgs.Empty); } newClient.WorkerSocket.BeginReceive(newClient.Buffer, 0, BasePacket.GetMaxPacketSize(), SocketFlags.None, new AsyncCallback(WaitForData), newClient); //Start accepting clients asynchronously again mainSocket.BeginAccept(OnClientConnected, null); } /// Waits for the upcoming messages from different clients and fires the proper event according to the packet type. /// /// private void WaitForData(IAsyncResult asyncResult) { ClientInfo sendingClient = null; try { //Take the client information from the asynchronous result resulting from the BeginReceive sendingClient = asyncResult.AsyncState as ClientInfo; // If client is disconnected, then throw a socket exception // with the correct error code. if (!IsConnected(sendingClient.WorkerSocket)) { throw new SocketException(ClientDisconnectedErrorCode); } //End the pending receive request sendingClient.WorkerSocket.EndReceive(asyncResult); //Fire the appropriate event FireMessageTypeEvent(sendingClient.ConvertBytesToPacket() as BasePacket); // Begin receiving data from this client sendingClient.WorkerSocket.BeginReceive(sendingClient.Buffer, 0, BasePacket.GetMaxPacketSize(), SocketFlags.None, new AsyncCallback(WaitForData), sendingClient); } catch (SocketException e) { if (e.ErrorCode == ClientDisconnectedErrorCode) { // Close the socket. if (sendingClient.WorkerSocket != null) { sendingClient.WorkerSocket.Close(); sendingClient.WorkerSocket = null; } // Remove it from the hash table. connectedClients.Remove(sendingClient.PlayerId); if (ClientDisconnectedEvent != null) { ClientDisconnectedEvent(this, new ClientDisconnectedEventArgs(sendingClient.PlayerId)); } } } catch (Exception e) { // Begin receiving data from this client sendingClient.WorkerSocket.BeginReceive(sendingClient.Buffer, 0, BasePacket.GetMaxPacketSize(), SocketFlags.None, new AsyncCallback(WaitForData), sendingClient); } } /// /// Broadcasts the input message to all the connected clients /// /// public void BroadcastMessage(BasePacket message) { byte[] bytes = message.ConvertToBytes(); foreach (ClientInfo client in connectedClients.Values) { client.WorkerSocket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, SendAsync, client); } } /// /// Sends the input message to the client specified by his ID. /// /// /// The message to be sent. /// The id of the client to receive the message. public void SendToClient(BasePacket message, int id) { byte[] bytes = message.ConvertToBytes(); (connectedClients[id] as ClientInfo).WorkerSocket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, SendAsync, connectedClients[id]); } private void SendAsync(IAsyncResult asyncResult) { ClientInfo currentClient = (ClientInfo)asyncResult.AsyncState; currentClient.WorkerSocket.EndSend(asyncResult); } /// Fires the event depending on the type of received packet /// /// The received packet. void FireMessageTypeEvent(BasePacket packet) { switch (packet.MessageType) { case MessageType.PositionUpdateMessage: if (PositionUpdateMessageEvent != null) { PositionUpdateMessageEvent(this, new PositionUpdateEventArgs(packet as PositionUpdatePacket)); } break; } } } The events fired are handled in a different class, here are the event handling code for the PositionUpdateMessage (Other handlers are irrelevant): private readonly Hashtable onlinePlayers = new Hashtable(); /// /// Constructor that creates a new instance of the GameController class. /// private GameController() { //Start the server server = new Thread(networkManager.StartServer); server.Start(); //Create an event handler for the NewClientEvent of networkManager networkManager.PositionUpdateMessageEvent += OnPositionUpdateMessageReceived; } /// /// this event handler is called when a client asks for movement. /// private void OnPositionUpdateMessageReceived(object sender, PositionUpdateEventArgs e) { Point currentLocation = ((PlayerData)onlinePlayers[e.PositionUpdatePacket.PlayerId]).Position; Point locationRequested = e.PositionUpdatePacket.Position; ((PlayerData)onlinePlayers[e.PositionUpdatePacket.PlayerId]).Position = locationRequested; // Broadcast the new position networkManager.BroadcastMessage(new PositionUpdatePacket { Position = locationRequested, PlayerId = e.PositionUpdatePacket.PlayerId }); }

    Read the article

  • AsyncListViewAdapter + SimplePager, why is inactive pager clearing the table?

    - by Jaroslav Záruba
    I'm trying to make CellTable work together with AsyncListViewAdapter<T> and SimplePager<T>. The data gets displayed, but when the pager should be 'deaf' (meaning when all existing data are displayed) it still receives clicks and, more importantly, makes the displayed data go away. Instead of my data 'loading' indicator gets displayed, and it keep loading and loading... Obviously nothing gets loaded, as it doesn't even call the onRangeChanged handler. I went through the code-snippets in this thread, but I can't see anything suspicions on what I've been doing. Is there some obvious answer to a rookie mistake? I shrinked my variable names, hopefully it won't wrap too much. protected class MyAsyncAdapter extends AsyncListViewAdapter<DTO> { @Override protected void onRangeChanged(ListView<DTO> v) { /* * doesn't even get called on [go2start/go2end] click :( */ Range r = v.getRange(); fetchData(r.getStart(), r.getLength()); } } private void addTable() { // table: CellTable<DTO> table = new CellTable<DTO>(10); table.addColumn(new Column<DTO, String>(new TextCell()) { @Override public String getValue(DTO myDto) { return myDto.getName(); } }, "Name"); // pager: SimplePager<DTO> pager = new SimplePager<DTO>(table); table.setPager(pager); adapter = new MyAsyncAdapter(); adapter.addView(table); // does not make any difference: // adapter.updateDataSize(0, false); // adapter.updateDataSize(10, true); VerticalPanel vPanel = new VerticalPanel(); vPanel.add(table); vPanel.add(pager); RootLayoutPanel.get().add(vPanel); } // success-handler of my fetching AsyncCallback @Override public void onSuccess(List<DTO> data) { // AsyncCallback<List<DTO>> has start field adapter.updateViewData(start, data.size(), data); if(data.size() < length) adapter.updateDataSize(start + data.size(), true); } Regards J. Záruba

    Read the article

  • CellTable + AsyncListViewAdapter<T>, stuck at 'loading' when paging

    - by Jaroslav Záruba
    Hi I'm trying to make CellTable, AsyncListViewAdapter<T> and SimplePager<T> working together. I managed to display my data, but whenever I click either "go to start" or "go to end" button I get that 'loading' indicator which stays there till the end of days. ( AsyncListViewAdapter<T>.onRangeChanged doesn't even get called this time.) As I have only single row in my data those two buttons should be (and appear to be) disabled. I went through the code-snippets in this thread, but I can't see nothing suspicions in what I've been doing. Is there some obvious answer to a rookie mistake? I shrinked my variable names, hopefully it won't wrap too much. protected class MyAsyncAdapter extends AsyncListViewAdapter<DTO> { @Override protected void onRangeChanged(ListView<DTO> v) { // doesn't get called on go2start/go2end :( Range r = v.getRange(); fetchData(r.getStart(), r.getLength()); } } private void addTable() { // table: CellTable<DTO> table = new CellTable<DTO>(10); table.addColumn(new Column<DTO, String>(new TextCell()) { @Override public String getValue(DTO namespace) { return namespace.getName(); } }, "Name"); // pager: SimplePager<DTO> pager = new SimplePager<DTO>(table); table.setPager(pager); adapter = new MyAsyncAdapter(); adapter.addView(table); // does not make any difference: // adapter.updateDataSize(0, false); // adapter.updateDataSize(10, true); VerticalPanel vPanel = new VerticalPanel(); vPanel.add(table); vPanel.add(pager); RootLayoutPanel.get().add(vPanel); } // success-handler of my fetching AsyncCallback @Override public void onSuccess(List<DTO> data) { // AsyncCallback<List<DTO>> has start field adapter.updateViewData(start, data.size(), data); if(data.size() < length) adapter.updateDataSize(start + data.size(), true); } Regards J. Záruba

    Read the article

  • Where do I handle asynchronous exceptions?

    - by Jurily
    Consider the following code: class Foo { // boring parts omitted private TcpClient socket; public void Connect(){ socket.BeginConnect(Host, Port, new AsyncCallback(cbConnect), quux); } private void cbConnect(IAsyncResult result){ // blah } } If socket throws an exception after BeginConnect returns and before cbConnect gets called, where does it pop up? Is it even allowed to throw in the background?

    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

  • Annonymous functions accessing local variables [ActionScript - Flex 3.5]

    - by Ali
    Hi All, I am having a situation with my actionscript/flex front end. for each (var sym:String in ["A","B","C"]) { const handler = function (data:Object):void { Alert.show(sym); } asyncCallback(handler); } I am expecting to have 3 Alert windows containing A, B and C. But the actual result is 3 alert windows all showing C ! I appreciate your comments. -A

    Read the article

  • PLINQ Adventure Land - WaitForAll

    - by adweigert
    PLINQ is awesome for getting a lot of work done fast, but one thing I haven't figured out yet is how to start work with PLINQ but only let it execute for a maximum amount of time and react if it is taking too long. So, as I must admit I am still learning PLINQ, I created this extension in that ignorance. It behaves similar to ForAll<> but takes a timeout and returns false if the threads don't complete in the specified amount of time. Hope this helps someone else take PLINQ further, it definitely has helped for me ...  public static bool WaitForAll<T>(this ParallelQuery<T> query, TimeSpan timeout, Action<T> action) { Contract.Requires(query != null); Contract.Requires(action != null); var exception = (Exception)null; var cts = new CancellationTokenSource(); var forAllWithCancellation = new Action(delegate { try { query.WithCancellation(cts.Token).ForAll(action); } catch (OperationCanceledException) { // NOOP } catch (AggregateException ex) { exception = ex; } }); var mrs = new ManualResetEvent(false); var callback = new AsyncCallback(delegate { mrs.Set(); }); var result = forAllWithCancellation.BeginInvoke(callback, null); if (mrs.WaitOne(timeout)) { forAllWithCancellation.EndInvoke(result); if (exception != null) { throw exception; } return true; } else { cts.Cancel(); return false; } }

    Read the article

  • Get Asynchronous HttpResponse through Silverlight (F#)

    - by jack2010
    I am a newbie with F# and SL and playing with getting asynchronous HttpResponse through Silverlight. The following is the F# code pieces, which is tested on VS2010 and Window7 and works well, but the improvement is necessary. Any advices and discussion, especially the callback part, are welcome and great thanks. module JSONExample open System open System.IO open System.Net open System.Text open System.Web open System.Security.Authentication open System.Runtime.Serialization [<DataContract>] type Result<'TResult> = { [<field: DataMember(Name="code") >] Code:string [<field: DataMember(Name="result") >] Result:'TResult array [<field: DataMember(Name="message") >] Message:string } // The elements in the list [<DataContract>] type ChemicalElement = { [<field: DataMember(Name="name") >] Name:string [<field: DataMember(Name="boiling_point") >] BoilingPoint:string [<field: DataMember(Name="atomic_mass") >] AtomicMass:string } //http://blogs.msdn.com/b/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx //http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!194.entry type System.Net.HttpWebRequest with member x.GetResponseAsync() = Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse) type RequestState () = let mutable request : WebRequest = null let mutable response : WebResponse = null let mutable responseStream : Stream = null member this.Request with get() = request and set v = request <- v member this.Response with get() = response and set v = response <- v member this.ResponseStream with get() = responseStream and set v = responseStream <- v let allDone = new System.Threading.ManualResetEvent(false) let getHttpWebRequest (query:string) = let query = query.Replace("'","\"") let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) request.Method <- "GET" request.ContentType <- "application/x-www-form-urlencoded" request let GetAsynResp (request : HttpWebRequest) (callback: AsyncCallback) = let myRequestState = new RequestState() myRequestState.Request <- request let asyncResult = request.BeginGetResponse(callback, myRequestState) () // easy way to get it to run syncrnously w/ the asynch methods let GetSynResp (request : HttpWebRequest) : HttpWebResponse = let response = request.GetResponseAsync() |> Async.RunSynchronously downcast response let RespCallback (finish: Stream -> _) (asynchronousResult : IAsyncResult) = try let myRequestState : RequestState = downcast asynchronousResult.AsyncState let myWebRequest1 : WebRequest = myRequestState.Request myRequestState.Response <- myWebRequest1.EndGetResponse(asynchronousResult) let responseStream = myRequestState.Response.GetResponseStream() myRequestState.ResponseStream <- responseStream finish responseStream myRequestState.Response.Close() () with | :? WebException as e -> printfn "WebException raised!" printfn "\n%s" e.Message printfn "\n%s" (e.Status.ToString()) () | _ as e -> printfn "Exception raised!" printfn "Source : %s" e.Source printfn "Message : %s" e.Message () let printResults (stream: Stream)= let result = try use reader = new StreamReader(stream) reader.ReadToEnd(); finally () let data = Encoding.Unicode.GetBytes(result); let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L let JsonSerializer = Json.DataContractJsonSerializer(typeof<Result<ChemicalElement>>) let result = JsonSerializer.ReadObject(stream) :?> Result<ChemicalElement> if result.Code<>"/api/status/ok" then raise (InvalidOperationException(result.Message)) else result.Result |> Array.iter(fun element->printfn "%A" element) let test = // Call Query (w/ generics telling it you wand an array of ChemicalElement back, the query string is wackyJSON too –I didn’t build it don’t ask me! let request = getHttpWebRequest "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]" //let response = GetSynResp request let response = GetAsynResp request (AsyncCallback (RespCallback printResults)) () ignore(test) System.Console.ReadLine() |> ignore

    Read the article

  • (C#) Label.Text = Struct.Value (Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException)

    - by Kyle
    I have an app that I'm working on that polls usage from an ISP (Download quota). I've tried threading this via 'new Thread(ThreaProc)' but that didn't work, now trying an IAsyncResult based approach which does the same thing... I've got no idea on how to rectify, please help? The need-to-know: // Global public delegate void AsyncPollData(ref POLLDATA pData); // Class scope: private POLLDATA pData; private void UpdateUsage() { AsyncPollData PollDataProc = new AsyncPollData(frmMain.PollUsage); IAsyncResult result = PollDataProc.BeginInvoke(ref pData, new AsyncCallback(UpdateDone), PollDataProc); } public void UpdateDone(IAsyncResult ar) { AsyncPollData PollDataProc = (AsyncPollData)ar.AsyncState; PollDataProc.EndInvoke(ref pData, ar); // The Exception occurs here: lblStatus.Text = pData.LastError; } public static void PollUsage(ref POLLDATA PData) { PData.LastError = "Some string"; return; }

    Read the article

  • Disable cache in Silverlight HttpWebRequest

    - by synergetic
    My Silverlight4 app is hosted in ASP.NET MVC 2 web application. I do web request through HttpWebRequest class but it gives back a result previously cached. How to disable this caching behavior? There are some links which talks about HttpWebRequest in .NET but Silverlight HttpWebrequest is different. Someone suggested to add unique dummy query string on every web request, but I'd prefer more elegant solution. I also tried the following, but it didn't work: _myHttpWebRequest.BeginGetRequestStream(new AsyncCallback(BeginRequest), new Guid()); In fact, by setting browser history settings it is possible to disable caching. See the following link: http://stackoverflow.com/questions/3027145/asp-net-mvc-with-sql-server-backend-returns-old-data-when-query-is-executed But asking a user to change browser settings is not an option for me.

    Read the article

  • GWT and java.io.Serializable

    - by Ethan Leroy
    Hello, In my GWT app I have the following model class: import com.google.gwt.user.client.rpc.IsSerializable; public class TestEntity implements IsSerializable { public String testString; } This class implements the GWT custom IsSerializable marker interface - which I really don't like, because I use my model classes not only for GWT. So I prefer java.io.Serializable. But if I modify the class to implement Serializable instead of IsSerializable, the GWT RPC mechanism doesn't work anymore. I don't get an error on the server side, but on the client AsyncCallback.onFailure is invoked. I am using... GWT 1.7.0. Spring 2.5.6.SEC01 Spring and GWT are configured as described here.

    Read the article

  • What sense does asynchronous IO make if the thread is blocked anyway (see example)

    - by codymanix
    Hello, I found an example for async ftp upload on msdn which does the following (snippet): // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback (EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); The thing what I do not understand here is, which sense does asynchronous IO make if the thread is blocked anyway with an explicit waithandle. I always thought the advantage of asynchronous IO was that the user/programm does not have to wait.

    Read the article

  • How to call WCF Service Method Asycroniously from Class file?

    - by stackuser1
    I've added WCF Service reference to my asp.net application and configured that reference to support asncronious calls. From asp.net code behind files, i'm able to call the service methods asyncroniously like the bellow sample code. protected void Button1_Click(object sender, EventArgs e) { PageAsyncTask pat = new PageAsyncTask(BeiginGetDataAsync, EndDataRetrieveAsync, null, null); Page.RegisterAsyncTask(pat); } IAsyncResult BeiginGetDataAsync(object sender, EventArgs e, AsyncCallback async, object extractData) { svc = new Service1Client(); return svc.BeginGetData(656,async, extractData); } void EndDataRetrieveAsync(IAsyncResult ar) { Label1.Text = svc.EndGetData(ar); } and in page directive added Async="true" In this scenario it is working fine. But from UI i'm not supposed to call the service methods directly. I need to call all service methods from a static class and from code behind file i need to invoke the static method. In this scenario what exactlly do i need to do?

    Read the article

  • Converting Asynchronous Programming Model (Begin/End methods) into event-based asynchronous model?

    - by David
    Let's say I have code that uses the Asynchronous Programming Model, i.e. it provides the following methods as a group which can be used synchronously or asynchronously: public MethodResult Operation(<method params>); public IAsyncResult BeginOperation(<method params>, AsyncCallback callback, object state); public MethodResult EndOperation(IAsyncResult ar); What I want to do is wrap this code with an additional layer that will transform it into the event-driven asynchronous model, like so: public void OperationAsync(<method params>); public event OperationCompletedEventHandler OperationCompleted; public delegate void OperationCompletedEventHandler(object sender, OperationCompletedEventArgs e); Does anyone have any guidance (or links to such guidance) on how to accomplish this?

    Read the article

  • Problems setting up an ASP.NET MVC site on IIS7 w/ Nhibernate

    - by Brandon
    When deploying my published website to the host (Its a shared hosting plan) I get this error: [NullReferenceException: Object reference not set to an instance of an object.] System.Web.PipelineStepManager.ResumeSteps(Exception error) +929 System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) +91 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +508 I found this question which describes my problem, but I'm not initializing NHibernate in Application_Start, it is already being done in Init. The only other cause of this error I can find is that the Global.asax file is inheriting from a class other than HttpApplication, but I'm not doing that either. This is pretty much the Global.asax file protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } public override void Init() { base.Init(); if (_wasNHibernateInitialized) return; // Initialize NHibernate // Other setup like the StructureMap initialization } Is there any other reason why an ASP.NET MVC application would give this error when being deployed to IIS7?

    Read the article

  • How to rebind another UDP socket port properly?

    - by Jollian
    When my client application launchs, it binds the UDP port like this: this.BindPort(5001); The BindPort method implement blow: public void BindPort(int port) { m_listener = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); IPEndPoint Point = new IPEndPoint( IPAddress.Any, Port ); m_listener.Bind( port); m_listener.BeginReceive( buff, 0, buff.Length, SocketFlags.None, new AsyncCallback( DataReceived ), buff ); } And when my server application commands client to bind to another UDP port(e.g. 5005). I call the same BindPort method in client. Then a exception occurs at DataReceived method. I think there must be a problem that I don't close the UDP port properly. But how can i close the UDP socket properly and rebind to another one. Thanks.

    Read the article

  • How can you tell the source of the data when using the Stream.BeginRead Method?

    - by xarzu
    When using the Stream.BeginRead Method, and you are reading from a stream into a memory, how is it determined where you are reading the data from? See: http://msdn.microsoft.com/en-us/library/system.io.stream.beginread.aspx In the list of parameters, I do not see one that tells where the data is being read from: Parameters buffer Type: System.Byte[] The buffer to read the data into. offset Type: System.Int32 The byte offset in buffer at which to begin writing data read from the stream. count Type: System.Int32 The maximum number of bytes to read. callback Type: System.AsyncCallback An optional asynchronous callback, to be called when the read is complete. state Type: System.Object A user-provided object that distinguishes this particular asynchronous read request from other requests.

    Read the article

  • How to invoke a delegate with a null parameter?

    - by Rodney Burton
    I get a null exception if I try to pass a null parameter to a delegate during an invoke. Here's what the code looks like: public void RequestPhoto() { WCF.Service.BeginGetUserPhoto(Contact.UserID, new AsyncCallback(RequestPhotoCB), null); } public void RequestPhotoCB(IAsyncResult result) { var photo = WCF.Service.EndGetUserPhoto(result); UpdatePhoto(photo); } public delegate void UpdatePhotoDelegate(Binary photo); public void UpdatePhoto(Binary photo) { if (InvokeRequired) { var d = new UpdatePhotoDelegate(UpdatePhoto); Invoke(d, new object[] { photo }); } else { var ms = new MemoryStream(photo.ToArray()); var bmp = new Bitmap(ms); pbPhoto.BackgroundImage = bmp; } } The problem is with the line: Invoke(d, new object[] { photo }); If the variable "photo" is null. What is the correct way to pass a null parameter during an invoke? Thanks!

    Read the article

  • Working with EnumSet class in GWT

    - by zenmonkey
    I am having trouble using EnumSet on the client side. I get this runtime error message: java.util.EnumSet.EnumSetImpl is not default instantiable (it must have a zero-argument constructor or no constructors at all) and has no custom serializer. Is this is a known issue? Here is what I am doing (basically a hello world app) Service: String echo (EnumSet<Names> name) throws IllegalArgumentException; Client: echoServ.echo (EnumSet.of(Names.JOHN), new AsyncCallback<String>() { ....... }); Shared enum class enum Names { JOHN, NUMAN, OBAMA }

    Read the article

  • How can I pass an object as a parameter in the google app engine RPC flow?

    - by jimmartens
    I'm building a pretty basic app, and one thing I want to do is pass an object as a parameter up through the service - async - impl instead of passing up a million separate parameters. so in async, I do something like this: import shared.Profile; ... public interface ProfileServiceAsync { public void addProfile(Profile inProf, AsyncCallback<Void> async); Now, profile is a class in com. ... .shared and I have the following in my ... .gwt.xml <source path='shared'/> That being said when I try to compile I get this error. [ERROR] Errors in 'file:/D:/projects/eclipse/workspace/.../src/com/.../client/ProfileServiceAsync.java' [ERROR] Line 11: No source code is available for type shared.Profile; did you forget to inherit a required module? Any ideas on this?

    Read the article

  • Socket c# not listen on port over internet?

    - by Nguy?n Van Th?ng
    Code server I have server listen on port 1450: //Using UDP sockets clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450); //Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc). clientSocket.Bind(ourEP); //Receive data from any IP. EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0)); byteData = new byte[1024]; //Receive data asynchornously. clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref remoteEP, new AsyncCallback(OnReceive), null); but code on not open port 1450 and client connect: otherPartyIP = new IPEndPoint(IPAddress.Parse(txtCallToIP.Text), 1450); otherPartyEP = (EndPoint)otherPartyIP; When i run code client and server in lan network it's ok. but run over network i check port 1450 in lan not open. tell me how open port 1450 in code server? thanks

    Read the article

  • System.Threading.ThreadAbortException executing WCF service

    - by SURESH GIRIRAJAN
    In one of our prod server we recently ran into issue when we went and update the web.config and try to browse the service. We started seeing the service was not responding and getting the following warning in the application log. Our service is WCF service, BizTalk orchestration exposed as service. We have other prod server where we never ran into this issue, so what’s different with this server. After going thru lot of forum and came up on some Microsoft service pack and hot fix which related to FCN. But I don’t want to apply any patch on this server then we need to do on all the other servers too. So solution is simple, I dropped the existing website, created a new site with different name with updated web.config browse the service. Then dropped that site and recreate the original web site and it worked fine without any issue. Event Viewer:  Event Type:        Warning Event Source:    ASP.NET 2.0.50727.0 Event Category:                Web Event Event ID:              1309 Date:                     6/6/2011 Time:                    5:41:42 PM User:                     N/A Computer:          PRODP02 Description: Event code: 3005 Event message: An unhandled exception has occurred. Event time: 6/6/2011 5:41:42 PM Event time (UTC): 6/6/2011 9:41:42 PM Event ID: a71769f42b304355a58c482bfec267f2 Event sequence: 3 Event occurrence: 1 Event detail code: 0  Application information:     Application domain: /LM/W3SVC/518296899/ROOT/PortArrivals-2-129518698821558995     Trust level: Full     Application Virtual Path: /TESTSVC     Application Path: D:\inetpub\wwwroot\RFID\TESTSVC\     Machine name: PRODP02  Process information:     Process ID: 8752     Process name: w3wp.exe     Account name: domain\BizTalk_Svc_Hostlso  Exception information:     Exception type: ThreadAbortException     Exception message: Thread was being aborted.  Request information:     Request URL: http://localhost:81/TESTSVC/TESTSVCS.svc     Request path: /TESTSVC/TESTSVCS.svc     User host address: 127.0.0.1     User:      Is authenticated: False     Authentication Type:      Thread account name: domain\BizTalk_Svc_Hostlso  Thread information:     Thread ID: 22     Thread account name: domain\BizTalk_Svc_Hostlso     Is impersonating: False     Stack trace:    at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)    at System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(Exception error)  at System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)    at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)  <Description>Handling an exception.</Description> <AppDomain>/LM/W3SVC/518296899/ROOT/TESTSVC-6-129518741899334691</AppDomain> <Exception> <ExceptionType>System.Threading.ThreadAbortException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType> <Message>Thread was being aborted.</Message> <StackTrace> at System.Threading.Monitor.Enter(Object obj) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest() at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state) at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2() at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke() at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks() at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state) at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) </StackTrace> <ExceptionString>System.Threading.ThreadAbortException: Thread was being aborted.    at System.Threading.Monitor.Enter(Object obj)    at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)    at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath)    at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()    at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()    at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)    at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()    at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()    at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()    at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)    at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)    at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)</ExceptionString>

    Read the article

  • C# 5 Async, Part 2: Asynchrony Today

    - by Reed
    The .NET Framework has always supported asynchronous operations.  However, different mechanisms for supporting exist throughout the framework.  While there are at least three separate asynchronous patterns used through the framework, only the latest is directly usable with the new Visual Studio Async CTP.  Before delving into details on the new features, I will talk about existing asynchronous code, and demonstrate how to adapt it for use with the new pattern. The first asynchronous pattern used in the .NET framework was the Asynchronous Programming Model (APM).  This pattern was based around callbacks.  A method is used to start the operation.  It typically is named as BeginSomeOperation.  This method is passed a callback defined as an AsyncCallback, and returns an object that implements IAsyncResult.  Later, the IAsyncResult is used in a call to a method named EndSomeOperation, which blocks until completion and returns the value normally directly returned from the synchronous version of the operation.  Often, the EndSomeOperation call would be called from the callback function passed, which allows you to write code that never blocks. While this pattern works perfectly to prevent blocking, it can make quite confusing code, and be difficult to implement.  For example, the sample code provided for FileStream’s BeginRead/EndRead methods is not simple to understand.  In addition, implementing your own asynchronous methods requires creating an entire class just to implement the IAsyncResult. Given the complexity of the APM, other options have been introduced in later versions of the framework.  The next major pattern introduced was the Event-based Asynchronous Pattern (EAP).  This provides a simpler pattern for asynchronous operations.  It works by providing a method typically named SomeOperationAsync, which signals its completion via an event typically named SomeOperationCompleted. The EAP provides a simpler model for asynchronous programming.  It is much easier to understand and use, and far simpler to implement.  Instead of requiring a custom class and callbacks, the standard event mechanism in C# is used directly.  For example, the WebClient class uses this extensively.  A method is used, such as DownloadDataAsync, and the results are returned via the DownloadDataCompleted event. While the EAP is far simpler to understand and use than the APM, it is still not ideal.  By separating your code into method calls and event handlers, the logic of your program gets more complex.  It also typically loses the ability to block until the result is received, which is often useful.  Blocking often requires writing the code to block by hand, which is error prone and adds complexity. As a result, .NET 4 introduced a third major pattern for asynchronous programming.  The Task<T> class introduced a new, simpler concept for asynchrony.  Task and Task<T> effectively represent an operation that will complete at some point in the future.  This is a perfect model for thinking about asynchronous code, and is the preferred model for all new code going forward.  Task and Task<T> provide all of the advantages of both the APM and the EAP models – you have the ability to block on results (via Task.Wait() or Task<T>.Result), and you can stay completely asynchronous via the use of Task Continuations.  In addition, the Task class provides a new model for task composition and error and cancelation handling.  This is a far superior option to the previous asynchronous patterns. The Visual Studio Async CTP extends the Task based asynchronous model, allowing it to be used in a much simpler manner.  However, it requires the use of Task and Task<T> for all operations.

    Read the article

  • Dynamically load and call delegates based on source data

    - by makerofthings7
    Assume I have a stream of records that need to have some computation. Records will have a combination of these functions run Sum, Aggregate, Sum over the last 90 seconds, or ignore. A data record looks like this: Date;Data;ID Question Assuming that ID is an int of some kind, and that int corresponds to a matrix of some delegates to run, how should I use C# to dynamically build that launch map? I'm sure this idea exists... it is used in Windows Forms which has many delegates/events, most of which will never actually be invoked in a real application. The sample below includes a few delegates I want to run (sum, count, and print) but I don't know how to make the quantity of delegates fire based on the source data. (say print the evens, and sum the odds in this sample) using System; using System.Threading; using System.Collections.Generic; internal static class TestThreadpool { delegate int TestDelegate(int parameter); private static void Main() { try { // this approach works is void is returned. //ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello"); int c = 0; int w = 0; ThreadPool.GetMaxThreads(out w, out c); bool rrr =ThreadPool.SetMinThreads(w, c); Console.WriteLine(rrr); // perhaps the above needs time to set up6 Thread.Sleep(1000); DateTime ttt = DateTime.UtcNow; TestDelegate d = new TestDelegate(PrintOut); List<IAsyncResult> arDict = new List<IAsyncResult>(); int count = 1000000; for (int i = 0; i < count; i++) { IAsyncResult ar = d.BeginInvoke(i, new AsyncCallback(Callback), d); arDict.Add(ar); } for (int i = 0; i < count; i++) { int result = d.EndInvoke(arDict[i]); } // Give the callback time to execute - otherwise the app // may terminate before it is called //Thread.Sleep(1000); var res = DateTime.UtcNow - ttt; Console.WriteLine("Main program done----- Total time --> " + res.TotalMilliseconds); } catch (Exception e) { Console.WriteLine(e); } Console.ReadKey(true); } static int PrintOut(int parameter) { // Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Delegate PRINTOUT waited and printed this:"+parameter); var tmp = parameter * parameter; return tmp; } static int Sum(int parameter) { Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread return parameter; } static int Count(int parameter) { Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread return parameter; } static void Callback(IAsyncResult ar) { TestDelegate d = (TestDelegate)ar.AsyncState; //Console.WriteLine("Callback is delayed and returned") ;//d.EndInvoke(ar)); } }

    Read the article

  • SQL Server - Physical connection is not usable Error Code: 19

    - by Harry
    Having trouble working out this SqlException: A transport-level error has occurred when sending the request to the server. (provider: Session Provider, error: 19 - Physical connection is not usable) Any ideas what this is about? Couldn't get any hits on google or msdn on this one. The connection is MARS and Asynchronous in my own SQL pool. But don't get all excited about that - that is old code that has been stable for a long time! Exception details pasted below: System.Data.SqlClient.SqlException occurred Message=A transport-level error has occurred when sending the request to the server. (provider: Session Provider, error: 19 - Physical connection is not usable) Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=20 LineNumber=0 Number=-1 Server=SERVER State=0 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParserStateObject.SNIWriteAsync(SNIHandle handle, SNIPacket packet, DbAsyncResult asyncResult) at System.Data.SqlClient.TdsParserStateObject.WriteSni() at System.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode) at System.Data.SqlClient.TdsParserStateObject.ExecuteFlush() at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.BeginExecuteNonQuery(AsyncCallback callback, Object stateObject) at CrawlAbout.Library.SQL.SQLAdapter.<ExecuteNonQueryTask>d__12.MoveNext() in D:\Work\Projects\CrawlAbout.com 2.0\CrawlAbout.Library.SQL\SQLAdapter.cs:line 149 InnerException:

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >