Exemple #1
0
            internal override async Task SendAsync(IOperation op, CancellationTokenPair token = default)
            {
                var mockConnectionPool = new Mock <IConnectionPool>();

                var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();

                mockConnectionPoolFactory
                .Setup(m => m.Create(It.IsAny <ClusterNode>()))
                .Returns(mockConnectionPool.Object);

                var clusterNode = new ClusterNode(new ClusterContext(), mockConnectionPoolFactory.Object,
                                                  new Mock <ILogger <ClusterNode> >().Object, new DefaultObjectPool <OperationBuilder>(new OperationBuilderPoolPolicy()),
                                                  new Mock <ICircuitBreaker>().Object,
                                                  new Mock <ISaslMechanismFactory>().Object,
                                                  new TypedRedactor(RedactionLevel.None),
                                                  new HostEndpointWithPort("127.0.0.1", 11210),
                                                  new NodeAdapter(),
                                                  NoopRequestTracer.Instance);

                await clusterNode.ExecuteOp(op, token).ConfigureAwait(false);

                if (_statuses.TryDequeue(out ResponseStatus status))
                {
                    (op as OperationBase)?.HandleOperationCompleted(AsyncState.BuildErrorResponse(0, status));
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
        private async Task AssertRetryThenSuccessAsync(OperationBase op, Exception exp)
        {
            var retryOrchestrator = CreateRetryOrchestrator();

            var bucketMock = new Mock <BucketBase>("fake", new ClusterContext(), new Mock <IScopeFactory>().Object,
                                                   retryOrchestrator, new Mock <ILogger>().Object, new Mock <IRedactor>().Object,
                                                   new Mock <IBootstrapperFactory>().Object, NoopRequestTracer.Instance, new Mock <IOperationConfigurator>().Object,
                                                   new BestEffortRetryStrategy());

            bucketMock.Setup(x => x.SendAsync(op, It.IsAny <CancellationTokenPair>())).Callback((IOperation op, CancellationTokenPair ct) =>
            {
                if (op.Completed.IsCompleted)
                {
                    Assert.True(false, "operation result should be reset before retry");
                }
                // complete the operation (ResponseStatus does not matter for this test)
                op.HandleOperationCompleted(AsyncState.BuildErrorResponse(op.Opaque, ResponseStatus.TemporaryFailure));
                if (op.Attempts == 1)
                {
                    throw exp;
                }
            }).Returns(op.Completed.AsTask());

            var tokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(2500));

            try
            {
                await retryOrchestrator.RetryAsync(bucketMock.Object, op, CancellationTokenPair.FromInternalToken(tokenSource.Token)).ConfigureAwait(false);
            }
            catch (Exception)
            {
                Assert.True(false, "Expected operation to succeed after retry");
            }
            Assert.True(op.Attempts > 1);
        }
Exemple #3
0
        // Override of this method so that we can handle the disconnection of a client
        protected override void EndReadMessage(IAsyncResult result)
        {
            AsyncState state = (AsyncState)result.AsyncState;
            int        len   = state._stream.EndRead(result);

            string str = System.Text.Encoding.Default.GetString(state._data);

            // If stream is 0 bytes long, the client disconnected.
            // We can remove it from the list.
            if (string.IsNullOrEmpty(str))
            {
                for (int i = connectionList.Count - 1; i >= 0; i--)
                {
                    // Using HashCode as an ID : Good idea or not ?
                    if (connectionList[i].Client.GetStream().GetHashCode() == state._stream.GetHashCode())
                    {
                        connectionList.Remove(connectionList[i]);
                        return;
                    }
                }
            }

            Trace.WriteLine("Received: " + str);
            state._queue.EnqueueEvent(str);

            BeginReadSize(state._stream, state._queue);
        }
        private void TimeoutHandler(object?state)
        {
            AsyncState a = (AsyncState)state !;

            _statesInFlight.TryRemove(a.Opaque, out _);
            a.Cancel(ResponseStatus.OperationTimeout);
        }
Exemple #5
0
        static void WriteCallback(IAsyncResult asyncResult)
        {
            AsyncState asyncState = (AsyncState)asyncResult.AsyncState;

            try
            {
                asyncState.FS.EndWrite(asyncResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine("EndWrite Error:" + ex.Message);
                asyncState.WaitHandle.Set();
                return;
            }

            Console.WriteLine("write to " + asyncState.FS.Position);
            //判断是否写完,未写完继续异步写
            if (asyncState.Offset + asyncState.WriteCount < asyncState.Buffer.Length)
            {
                asyncState.Offset += asyncState.WriteCount;
                int writeSize = asyncState.WriteCount;
                if (asyncState.FS.Position + asyncState.WriteCount > asyncState.Buffer.Length)
                {
                    writeSize = (int)((long)asyncState.Buffer.Length - asyncState.FS.Position);
                }
                asyncState.FS.BeginWrite(asyncState.Buffer, asyncState.Offset, writeSize, WriteCallback, asyncState);
            }
            else
            {                //写完发出完成信号
                asyncState.WaitHandle.Set();
            }
        }
        private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _mode = mode;
            _options = options;

            if (_useAsyncIO)
                _asyncState = new AsyncState();

            // Translate the arguments into arguments for an open call.
            Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, options); // FileShare currently ignored

            // If the file gets created a new, we'll select the permissions for it.  Most Unix utilities by default use 666 (read and 
            // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out
            // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the
            // actual permissions will typically be less than what we select here.
            const Interop.Sys.Permissions OpenPermissions =
                Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR |
                Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP |
                Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH;

            // Open the file and store the safe handle.
            return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions);
        }
        public string Send(string command, bool waitForResponse = true)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            if (this.IsOpen)
            {
                this.m_serialPort.DiscardOutBuffer();
                this.m_serialPort.DiscardInBuffer();

                var state = new AsyncState(this.m_serialPort, Encoding.ASCII.GetBytes(string.Concat(command, this.NewLine)));
                this.m_serialPort.BaseStream.BeginWrite(state.Buffer, 0, state.Buffer.Length, m_endWriteCallback, state);

                if (waitForResponse)
                {
                    state = new AsyncState(this.m_serialPort);
                    lock (state)
                    {
                        this.m_serialPort.BaseStream.BeginRead(state.Buffer, 0, state.Buffer.Length, m_endReadCallback, state);
                        if (Monitor.Wait(state, this.Timeout))
                        {
                            return(state.Data);
                        }

                        throw new TimeoutException();
                    }
                }

                return(null);
            }

            throw new IOException("Serial port is closed.");
        }
Exemple #8
0
        public Task <TOut> Async <TOut, TIn>(Func <TIn, TOut> async, TIn state = default(TIn))
        {
            var currentThread      = Thread.CurrentThread;
            var currentHttpContext = System.Web.HttpContext.Current;
            var currentState       = new AsyncState <TIn>(currentThread, currentHttpContext, state);

            return(Task <TOut> .Factory.StartNew
                   (
                       o =>
            {
                var s = (AsyncState <TIn>)o;
                if (s?.Thread != null && s.HttpContext != null)
                {
                    var culture = s.Thread.CurrentCulture;
                    if (culture.Name == "th-TH" || culture.Name == "th")
                    {
                        culture.DateTimeFormat = new DateTimeFormatInfo
                        {
                            Calendar = CultureInfo.InvariantCulture.Calendar
                        };
                    }
                    Thread.CurrentThread.CurrentCulture = culture;
                    Thread.CurrentThread.CurrentUICulture = culture;
                    System.Web.HttpContext.Current = s.HttpContext;
                    return async(s.State);
                }
                return default(TOut);
            },
                       currentState
                   ));
        }
    protected override void Beat()
    {
        IInternalMessage message = SystemMessageQueue.Instance.Poll();

        if (message != null)
        {
            switch (message.GetMessageId())
            {
            case AsyncTaskMessage.ASYNC_MESSAGE_ID:
            {
                AsyncTaskMessage asyncTaskMessage = message as AsyncTaskMessage;
                AsyncState       state            = asyncTaskMessage.State;
                IAsyncTask       asyncTask        = asyncTaskMessage.AsyncTask;
                if (state == AsyncState.DoAsync)
                {
                    throw new ApplicationException(string.Format("asyncTask:{0} [DoAsyncTask] infinite loop.", asyncTask.GetType().FullName));
                }
                AsyncManager.Instance.ExecuteAsyncTask(state, asyncTask);
                break;
            }

            default:
            {
                break;
            }
            }
        }
    }
Exemple #10
0
        private void HandleResponse(IAsyncResult result)
        {
            AsyncState state = (AsyncState)result.AsyncState;

            try
            {
                HttpWebResponse response = state.Request.EndGetResponse(result) as HttpWebResponse;
                using (Response r = HandleResponse(response, state.Method, state.IncludeBody, state.RequestModifier, state.RetryLevel))
                {
                    if (r != null)
                    {
                        TryCallResponseCallback(r);
                        TryCallCompleteCallback(r);
                    }
                }
            }
            catch (WebException ex)
            {
                Response response = new Response((HttpWebResponse)ex.Response, Session, state.RetryLevel);
                HandleWebExceptionResult exResult = HandleWebException(ex, state.Url, state.Method, state.IncludeBody, state.RequestModifier, state.RetryLevel);
                if (!exResult.Retried)
                {
                    if (ex.Status != WebExceptionStatus.RequestCanceled)
                    {
                        TryCallErrorCallback(ex, response);
                    }
                    TryCallCompleteCallback(response);
                }
            }
            finally
            {
                CurrentAsyncRequest = null;
            }
        }
Exemple #11
0
        private void HandleGetRequestStream(IAsyncResult result)
        {
            AsyncState state = (AsyncState)result.AsyncState;

            try
            {
                using (Stream requestStream = state.Request.EndGetRequestStream(result))
                {
                    WriteBody(requestStream, state.Request, state.IncludeBody);
                }

                state.Request.BeginGetResponse(HandleResponse, state);
            }
            catch (WebException ex)
            {
                Response response = new Response((HttpWebResponse)ex.Response, Session, state.RetryLevel);
                HandleWebExceptionResult exResult = HandleWebException(ex, state.Url, state.Method, state.IncludeBody, state.RequestModifier, state.RetryLevel);
                if (!exResult.Retried)
                {
                    if (ex.Status != WebExceptionStatus.RequestCanceled)
                    {
                        TryCallErrorCallback(ex, response);
                    }
                    TryCallCompleteCallback(response);
                }
            }
            finally
            {
                CurrentAsyncRequest = null;
            }
        }
Exemple #12
0
        /// <summary>
        /// Do actual async request.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="includeBody">Indicates a redirect where the available POST data should be ignored (if false).</param>
        /// <param name="requestModifier"></param>
        /// <param name="retryLevel"></param>
        /// <returns>Always null.</returns>
        protected override Response DoRequest(Uri url, string method, bool includeBody, Action <HttpWebRequest> requestModifier, int retryLevel = 0)
        {
            CurrentAsyncRequest = SetupRequest(url, method, includeBody, requestModifier);

            AsyncState state = new AsyncState
            {
                IncludeBody     = includeBody,
                Method          = method,
                RequestModifier = requestModifier,
                RetryLevel      = retryLevel,
                Url             = url,
                Request         = CurrentAsyncRequest
            };

            if (includeBody && BodyData != null)
            {
                CurrentAsyncRequest.BeginGetRequestStream(HandleGetRequestStream, state);
            }
            else
            {
                ApplyHeadersReadyInterceptors(CurrentAsyncRequest);
                CurrentAsyncRequest.BeginGetResponse(HandleResponse, state);
            }

            return(null);
        }
Exemple #13
0
        private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _mode    = mode;
            _options = options;

            if (_useAsyncIO)
            {
                _asyncState = new AsyncState();
            }

            // Translate the arguments into arguments for an open call.
            Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, options); // FileShare currently ignored

            // If the file gets created a new, we'll select the permissions for it.  Most utilities by default use 666 (read and
            // write for all). However, on Windows it's possible to write out a file and then execute it.  To maintain that similarity,
            // we use 766, so that in addition the user has execute privileges. No matter what we choose, it'll be subject to the umask
            // applied by the system, such that the actual permissions will typically be less than what we select here.
            const Interop.Sys.Permissions openPermissions =
                Interop.Sys.Permissions.S_IRWXU |
                Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP |
                Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH;

            // Open the file and store the safe handle.
            return(SafeFileHandle.Open(_path, openFlags, (int)openPermissions));
        }
        private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _mode    = mode;
            _options = options;

            if (_useAsyncIO)
            {
                _asyncState = new AsyncState();
            }

            // Translate the arguments into arguments for an open call.
            Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options);

            // If the file gets created a new, we'll select the permissions for it.  Most Unix utilities by default use 666 (read and
            // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out
            // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the
            // actual permissions will typically be less than what we select here.
            const Interop.Sys.Permissions OpenPermissions =
                Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR |
                Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP |
                Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH;

            // Open the file and store the safe handle.
            return(SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions));
        }
        public static void Execute()
        {
            if (_enumerator == null)
            {
                return;
            }

            if (Collab.instance.AnyJobRunning())
            {
                return;
            }

            try
            {
                if (!_enumerator.MoveNext())
                {
                    End();
                }
                else
                {
                    _nextState = _enumerator.Current;
                }
            }
            catch (Exception)
            {
                Debug.LogError("Something Went wrong with the test framework itself");
                throw;
            }
        }
 void OnAsyncStateChange(object sender, GXAsyncWork work, object[] parameters, AsyncState state, string text)
 {
     foreach (AsyncStateChangeEventHandler e in Events)
     {
         e(sender, work, parameters, state, text);
     }
 }
Exemple #17
0
        public static void AsyncWrite(string content, string path)
        {
            byte[]     toWriteBytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(content);
            string     filePath     = path;
            AsyncState state        = new AsyncState
            {
                Offset     = 0,
                Buffer     = toWriteBytes,
                WaitHandle = new ManualResetEvent(false),
            };

            state.WriteCount = 26;// toWriteBytes.Length;

            //FileStream实例
            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize, FileOptions.Asynchronous))
            {
                state.FS = fileStream;

                fileStream.BeginWrite(toWriteBytes, 0, state.WriteCount, WriteCallback, state);
                //等待写完毕或者出错发出的继续信号
                state.WaitHandle.WaitOne();
            }
            //Console.WriteLine("Done");
            //Console.Read();
        }
Exemple #18
0
            private void startClient()
            {
                // socket 绑定 ip 和端口
                IPAddress ip           = IPAddress.Parse(this.ownerForm.ip);
                int       port         = int.Parse(this.ownerForm.port);
                Socket    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 尝试连接
                try
                {
                    clientSocket.Connect(new IPEndPoint(ip, port));
                    this.chatTextBox.Text += String.Format("{0} 系统 > 开始连接至 {1}:{2}\r\n", DateTime.Now.ToString(), Convert.ToString(ip), port);
                }
                catch
                {
                    this.chatTextBox.Text  += String.Format("{0} 系统 > 连接失败\r\n", DateTime.Now.ToString());
                    this.sendButton.Enabled = false;
                    return;
                }
                this.chatTextBox.Text += String.Format("{0} 系统 > 连接建立,客户端 Socket 地址为 {1}\r\n", DateTime.Now.ToString(), clientSocket.LocalEndPoint.ToString());
                // 发送身份信息
                string reportMessage = JsonConvert.SerializeObject(new Data()
                {
                    from = this.clientName, data = "hello!", time = DateTime.Now.ToString()
                });

                //string reportMessage = String.Format("ClientName:{0}", this.clientName);
                clientSocket.Send(Encoding.UTF8.GetBytes(reportMessage));

                this.clientSocket = clientSocket;
                this.clientStatus = "active";

                //AsyncReceive();
                // 开启后台工作接收服务端转发的数据并更新 chatLabel
                BackgroundWorker worker = new BackgroundWorker();

                worker.WorkerReportsProgress = true;
                worker.DoWork += new DoWorkEventHandler((sender, e) =>
                {
                    while (this.clientStatus != "close")
                    {
                        Thread.Sleep(50);
                    }
                    //MessageBox.Show("DoWorker quit");
                });
                worker.ProgressChanged += new ProgressChangedEventHandler((sender, e) =>
                {
                    Data recvData = (Data)e.UserState;
                    newMessageDisplay(recvData);
                });
                worker.RunWorkerAsync();

                AsyncState asyncState = new AsyncState()
                {
                    socket = clientSocket, byteData = new byte[1024], worker = worker
                };

                // offset=0, size=1024
                this.clientSocket.BeginReceive(asyncState.byteData, 0, asyncState.byteData.Length, SocketFlags.None, new AsyncCallback(AsyncReceiveCallBack), asyncState);
            }
Exemple #19
0
        public void Write(byte reportId, byte[] data, WriteCallback callback, int timeout)
        {
            var d          = new _WriteDelegate(Write);
            var asyncState = new AsyncState(d, callback);

            d.BeginInvoke(reportId, data, timeout, _EndWrite, asyncState);
        }
Exemple #20
0
        public void Read(ReadCallback callback, int timeout)
        {
            var d          = new _ReadDelegate(Read);
            var asyncState = new AsyncState(d, callback);

            d.BeginInvoke(timeout, _EndRead, asyncState);
        }
Exemple #21
0
        private static void EndRecv(IAsyncResult asyncResult)
        {
            AsyncState state = (AsyncState)asyncResult.AsyncState;

            try
            {
                m_sListen.EndReceiveFrom(asyncResult, ref state.EndPoint);
                Random random = new Random();
                if (state.Buffer.Length > 20)
                {
                    string recString = Encoding.Default.GetString(state.Buffer);
                    Match  mat       = reg.Match(recString.Trim(), 0);
                    //recString.IndexOf(',');
                    //recString.IndexOf(':');
                    if (mat.Success)
                    {
                        updateLastTimedDelegate.BeginInvoke(mat, UpdateLastTimeComeplete, updateLastTimedDelegate);
                        sendTankLevelDelegate.BeginInvoke(mat, SendTankLevelComeplete, sendTankLevelDelegate);
                    }
                }

                PostRecv(state.EndPoint);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                PostRecv(state.EndPoint);
            }

            //  PostSend(state.Buffer, state.Offset, state.Size, state.EndPoint);
        }
Exemple #22
0
 static void _PostAction(MainWindow mw, AsyncState async_state)
 {
     mw.response_content_type      = (async_state[StateItem.ResponseContentType] as string) !;
     mw.tblResponseHeaderLeft.Text = $"HTTP: {async_state[StateItem.ResponseStatus]!}";
     mw.tblResponseBodyLeft.Text   = mw.response_content_type;
     mw.tbxResponseHeader.Text     = (async_state[StateItem.ResponseHeader] as string) !;
     mw.tbxResponseBody.Text       = (async_state[StateItem.ResponseBody] as string) !;
 }
Exemple #23
0
 public BaseThreadPoolResult()
 {
     _state             = AsyncState.Stopped;
     _error             = null;
     _completedHandlers = null;
     _failedHandlers    = null;
     SyncRoot           = new object();
 }
Exemple #24
0
 /// <summary>
 /// Preko ove metode se pokrece GetResults, ali asinkrono.
 /// Metodi se predaje delegat (callback) koji ce se pozvati kada se storica izvrsi.
 /// Unutar callback metode, potrebno je pozvati EndExecute da bi se dobio rezultat storice (ukoliko je doslo do greske, pozivanje EndExecute dize taj exception).
 /// </summary>
 public static IAsyncResult BeginExecute(System.String query, System.Int32? languageId, System.Int32? top, System.Int32? startRowIndex, System.Int32? maximumRows, System.Int32? orderBy,out System.String queryMessage, AsyncCallback callback, object state)
 {
     ExecuteDelegate delegat = Execute;
     AsyncState asyncState = new AsyncState();
     asyncState.delegat = delegat;
     asyncState.state = state;
     return delegat.BeginInvoke(query, languageId, top, startRowIndex, maximumRows, orderBy, out queryMessage, callback, asyncState);
 }
Exemple #25
0
 /// <summary>
 /// Preko ove metode se pokrece InsertAdvertRaw, ali asinkrono.
 /// Metodi se predaje delegat (callback) koji ce se pozvati kada se storica izvrsi.
 /// Unutar callback metode, potrebno je pozvati EndExecute da bi se dobio rezultat storice (ukoliko je doslo do greske, pozivanje EndExecute dize taj exception).
 /// </summary>
 public static IAsyncResult BeginExecute(System.Int32? AgencyId, System.Int32? GenerationId, System.Int32? LanguageId, System.String HashCode, System.String SystemStatus, System.Boolean? Active, System.String Source, System.String Language, System.String GroupType, System.String GroupSubType, System.String SourceCategory, System.String Title, System.String AccommType, System.String AccommSubType, System.String VacationType, System.String AdvertCode, System.String UrlLink, System.String PictureUrl, System.String Stars, System.String LocationDesc, System.String Country, System.String Region, System.String Subregion, System.String Island, System.String City, System.String PriceOld, System.String PriceFrom, System.String PriceDesc, System.String Date1, System.String Date2, System.String DateDesc, System.String DaysNum, System.String Description, System.String Activities, System.String Facilities, System.String Beach, System.String BeachDistanceM, System.String DistanceFromCentreM, System.String PetsDesc, System.String InfoDesc, AsyncCallback callback, object state)
 {
     ExecuteDelegate delegat = Execute;
     AsyncState asyncState = new AsyncState();
     asyncState.delegat = delegat;
     asyncState.state = state;
     return delegat.BeginInvoke(AgencyId, GenerationId, LanguageId, HashCode, SystemStatus, Active, Source, Language, GroupType, GroupSubType, SourceCategory, Title, AccommType, AccommSubType, VacationType, AdvertCode, UrlLink, PictureUrl, Stars, LocationDesc, Country, Region, Subregion, Island, City, PriceOld, PriceFrom, PriceDesc, Date1, Date2, DateDesc, DaysNum, Description, Activities, Facilities, Beach, BeachDistanceM, DistanceFromCentreM, PetsDesc, InfoDesc, callback, asyncState);
 }
Exemple #26
0
 /// <summary>
 /// Preko ove metode se pokrece GetAdvertRaw, ali asinkrono.
 /// Metodi se predaje delegat (callback) koji ce se pozvati kada se storica izvrsi.
 /// Unutar callback metode, potrebno je pozvati EndExecute da bi se dobio rezultat storice (ukoliko je doslo do greske, pozivanje EndExecute dize taj exception).
 /// </summary>
 public static IAsyncResult BeginExecute(System.Int32? Id, System.Guid? userId, AsyncCallback callback, object state)
 {
     ExecuteDelegate delegat = Execute;
     AsyncState asyncState = new AsyncState();
     asyncState.delegat = delegat;
     asyncState.state = state;
     return delegat.BeginInvoke(Id, userId, callback, asyncState);
 }
Exemple #27
0
        private void OnAsyncDone(IAsyncResult ar)
        {
            AsyncState state = (AsyncState)ar.AsyncState;

            state.Router.ReplyTo(state.Query, new TestAck("async-complete"));
            state.Session.OnAsyncFinished();
            AsyncTimer.EndTimer(ar);
        }
Exemple #28
0
 /// <summary>
 /// Preko ove metode se pokrece InsertRequest, ali asinkrono.
 /// Metodi se predaje delegat (callback) koji ce se pozvati kada se storica izvrsi.
 /// Unutar callback metode, potrebno je pozvati EndExecute da bi se dobio rezultat storice (ukoliko je doslo do greske, pozivanje EndExecute dize taj exception).
 /// </summary>
 public static IAsyncResult BeginExecute(System.String URL, System.String Osoba, System.String Email, System.String Telefon, System.DateTime? VrijemeUnosa, AsyncCallback callback, object state)
 {
     ExecuteDelegate delegat = Execute;
     AsyncState asyncState = new AsyncState();
     asyncState.delegat = delegat;
     asyncState.state = state;
     return delegat.BeginInvoke(URL, Osoba, Email, Telefon, VrijemeUnosa, callback, asyncState);
 }
Exemple #29
0
        private void startServer()
        {
            IPAddress ip           = IPAddress.Parse(this.ip);
            Socket    serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                serverSocket.Bind(new IPEndPoint(ip, int.Parse(this.port)));
            }
            catch (Exception e)
            {
                MessageBox.Show("绑定服务器失败,原因:\r\n" + e.ToString());
                return;
            }
            serverSocket.Listen(15);

            // 在 socketList 中加入服务器信息
            SocketInfo serverInfo = new SocketInfo();

            serverInfo.name      = "server";
            serverInfo.ip        = this.ip;
            serverInfo.port      = this.port;
            serverInfo.character = "server";
            this.socketInfoList.Add(serverSocket.LocalEndPoint.ToString(), serverInfo);
            this.socketList.Add(serverSocket.LocalEndPoint.ToString(), serverSocket);
            // 设置服务器状态为激活
            this.serverStatus = "active";

            // 更新 socket 连接信息表
            SocketContInfoUpdate();
            // 开启 backgroundworker 运行异步监听连接请求并报告进展
            BackgroundWorker worker = new BackgroundWorker();

            worker.WorkerReportsProgress = true;
            // 让 DoWork 空转,使用它的 reportProgress 功能,之后可以把异步的函数换成同步让 DoWork 真正起到作用
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                while (this.serverStatus != "close")
                {
                    Thread.Sleep(50);
                }
                MessageBox.Show("server quit");
            });
            worker.ProgressChanged += new ProgressChangedEventHandler((sender, e) =>
            {
                SocketContInfoUpdate();
            });
            worker.RunWorkerAsync();

            AsyncState asyncState = new AsyncState()
            {
                socket = serverSocket, worker = worker
            };

            serverSocket.BeginAccept(new AsyncCallback(AsyncAcceptCallback), asyncState);

            MessageBox.Show("服务端建立成功,开始监听...");
        }
Exemple #30
0
        private void AsyncAcceptCallback(IAsyncResult iar)
        {
            // 结束异步监听进程并取得建立连接的 socket
            AsyncState asyncstate = (AsyncState)iar.AsyncState;
            Socket     service    = asyncstate.socket.EndAccept(iar);
            // 建立一个新的监听进程
            AsyncState asyncstateNew = new AsyncState()
            {
                socket = asyncstate.socket, worker = asyncstate.worker
            };

            asyncstate.socket.BeginAccept(new AsyncCallback(AsyncAcceptCallback), asyncstateNew);
            // 接受客户端发来的第一个表明身份的数据包
            byte[] recvByte = new byte[1024];
            service.Receive(recvByte);
            Data recvData = new Data();

            try
            {
                recvData = JsonConvert.DeserializeObject <Data>(Encoding.UTF8.GetString(recvByte));
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return;
            }
            MessageBox.Show(JsonConvert.SerializeObject(recvData));
            if (recvData.from.Length == 0)
            {
                MessageBox.Show("数据包格式不正确,连接已阻止");
                service.Shutdown(SocketShutdown.Both);
                service.Close();
                return;
            }
            else
            {
                // 在 socketList 中加入客户端信息
                SocketInfo client     = new SocketInfo();
                string     IPEndPoint = service.RemoteEndPoint.ToString();
                client.name      = recvData.from;
                client.ip        = IPEndPoint.Split(':')[0];
                client.port      = IPEndPoint.Split(':')[1];
                client.character = "client";
                this.socketList.Add(IPEndPoint, service);
                this.socketInfoList.Add(IPEndPoint, client);
                MessageBox.Show(String.Format("与{0}建立连接", client.name));
                // 更新 socket 连接信息表
                asyncstate.worker.ReportProgress(1);
            }

            // 开始异步接收进程
            AsyncState recv_asyncState = new AsyncState()
            {
                socket = service, byteData = new byte[1024], worker = asyncstate.worker
            };

            service.BeginReceive(recv_asyncState.byteData, 0, recv_asyncState.byteData.Length, SocketFlags.None, new AsyncCallback(AsyncReceiveCallback), recv_asyncState);
        }
Exemple #31
0
 public void ReadXmlElementAsync(Action<XmlParserResult> result, bool allowText)
 {
     if (state != AsyncState.None) throw new InvalidOperationException("Already reading");
     if (allowText)
         state = AsyncState.AllowText;
     gotResultCallback = result;
     Origin.BufferedAsync = false;
     Read();
 }
 public void PopulateBinding(News binding, string Url)
 {
     var state = new AsyncState();
     var request = WebRequest.Create(Url) as HttpWebRequest;
     request.Accept = "application/json"; //atom+xml";
     state.request = request;
     state.binding = binding;
     request.BeginGetResponse(HandleNewsResult, state);
 }
Exemple #33
0
        protected void BeginReadSize(NetworkStream stream, Queue queue)
        {
            int intSize = sizeof(int);

            byte[]     bDataLength = new byte[intSize];
            AsyncState state       = new AsyncState(bDataLength, stream, queue);

            stream.BeginRead(bDataLength, 0, bDataLength.Length, EndReadSize, state);
        }
 protected override void Completed()
 {
     if (_state == null)
     {
         return;
     }
     _state.onComplete  -= Complete;
     _state.onTerminate -= Complete;
     _state              = null;
 }
		public AsyncRecord(AsyncScheduler scheduler, IFuture cacheKeyToEvict, IFuture future)
		{
			this._cacheKeyToEvict = cacheKeyToEvict;
			this._future = future;
			this.scheduler = scheduler;
			this._present = null;
			this.asyncState = AsyncState.Prequeued;
			this.queuePriority = 0;
			this.qtpRef = new AsyncRef(this, "qRef");
		}
Exemple #36
0
 public AsyncRecord(AsyncScheduler scheduler, IFuture cacheKeyToEvict, IFuture future)
 {
     this.cacheKeyToEvict = cacheKeyToEvict;
     this.future          = future;
     this.scheduler       = scheduler;
     present       = null;
     asyncState    = AsyncState.Prequeued;
     queuePriority = 0;
     qtpRef        = new AsyncRef(this, "qRef");
 }
Exemple #37
0
 public override string ToString()
 {
     try
     {
         return(AsyncState == null?base.ToString() : AsyncState.ToString());
     }
     catch (Exception)
     {
         return(base.ToString());
     }
 }
Exemple #38
0
        public void Add(AsyncState state, int timeoutMilliseconds)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            _statesInFlight.TryAdd(state.Opaque, state);

            state.Timer = new Timer(TimeoutHandler, state, timeoutMilliseconds, Timeout.Infinite);
        }
Exemple #39
0
 public MultiplexAwaiter(bool completed)
 {
     if (!completed)
     {
         _asyncState = new AsyncState();
     }
     else
     {
         _asyncState = null;
     }
 }
Exemple #40
0
        public static string AsyncRead(string filePath)
        {
            // string filePath = "c:\\test.txt";
            //以只读方式打开文件流
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.Asynchronous))
            {
                var buffer = new byte[bufferSize];

                //构造BeginRead需要传递的状态
                AsyncState asyncState = new AsyncState() { FS = fileStream, Buffer = buffer, WaitHandle = new ManualResetEvent(false) };
                asyncState.Rs = new List<byte>();

                //异步读取
                IAsyncResult asyncResult = fileStream.BeginRead(buffer, 0, bufferSize, new AsyncCallback(AsyncReadCallback), asyncState);
                asyncState.WaitHandle.WaitOne();
                //Console.WriteLine("read complete");
                return Encoding.UTF8.GetString(asyncState.Rs.ToArray());
            }
        }
 /// <summary>
 /// 指定异步任务状态,并从指定的状态开始执行,必须由主线程来调用
 /// </summary>
 /// <param name="state">指定异步任务的状态</param>
 /// <param name="asyncTask">异步任务对象</param>
 public void ExecuteAsyncTask(AsyncState state, IAsyncTask asyncTask)
 {
     switch (state)
     {
         case AsyncState.BeforeAsync:
             {
                 //异步开始前执行,由主线程调用
                 AsyncState newState = asyncTask.BeforeAsyncTask();
                 if (newState == AsyncState.BeforeAsync)
                 {
                     throw new ApplicationException(string.Format("asyncTask:{0} [BeforeAsyncTask] infinite loop.", asyncTask.GetType().FullName));
                 }
                 this.ExecuteAsyncTask(newState, asyncTask);
                 break;
             }
         case AsyncState.DoAsync:
             {
                 //需要异步执行,委托线程池来执行该任务
                 ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncExecute), asyncTask);
                 break;
             }
         case AsyncState.AfterAsync:
             {
                 AsyncState newState = asyncTask.AfterAsyncTask();
                 if (newState == AsyncState.AfterAsync)
                 {
                     throw new ApplicationException(string.Format("asyncTask:{0} [AfterAsyncTask] infinite loop.", asyncTask.GetType().FullName));
                 }
                 this.ExecuteAsyncTask(newState, asyncTask);
                 break;
             }
         default:
             {
                 break;
             }
     }
 }
Exemple #42
0
        public static void AsyncWrite(string content, string path)
        {
            byte[] toWriteBytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(content);
            string filePath = path;
            AsyncState state = new AsyncState
            {
                Offset = 0,
                Buffer = toWriteBytes,
                WaitHandle = new ManualResetEvent(false),
            };
            state.WriteCount = 26;// toWriteBytes.Length;

            //FileStream实例
            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize, FileOptions.Asynchronous))
            {
                state.FS = fileStream;

                fileStream.BeginWrite(toWriteBytes, 0, state.WriteCount, WriteCallback, state);
                //等待写完毕或者出错发出的继续信号
                state.WaitHandle.WaitOne();
            }
            //Console.WriteLine("Done");
            //Console.Read();
        }
Exemple #43
0
        private void InternalBeginReceive()
        {
            m_AsyncState |= AsyncState.Pending;

            m_Socket.BeginReceive( m_RecvBuffer, 0, m_RecvBuffer.Length, SocketFlags.None, m_OnReceive, m_Socket );
        }
 void OnAsyncStateChange(object sender, GXAsyncWork work, object[] parameters, AsyncState state, string text)
 {
     panel1.Visible = panel2.Visible = MediaFrame.Visible = state != AsyncState.Start;
     ConnectingPanel.Visible = state == AsyncState.Start;
     if (state != AsyncState.Start)
     {
         if (state == AsyncState.Cancel)
         {
             Handled.Set();
             this.DialogResult = DialogResult.None;
         }
         //Close dlg if user has not cancel the connection and no error are occured.
         else if (state == AsyncState.Finish)
         {
             this.DialogResult = DialogResult.OK;
         }
     }
 }
Exemple #45
0
		private void Receive_Start()
		{
			try {
				bool result = false;

				do {
					lock ( m_AsyncLock ) {
						if ( ( m_AsyncState & ( AsyncState.Pending | AsyncState.Paused ) ) == 0 ) {
							m_AsyncState |= AsyncState.Pending;
							result = !m_Socket.ReceiveAsync( m_ReceiveEventArgs );

							if ( result )
								Receive_Process( m_ReceiveEventArgs );
			}
					}
				} while ( result );
				} catch ( Exception ex ) {
					TraceException( ex );
					Dispose( false );
				}
			}
		internal void ProcessSynchronously()
		{
			Monitor.Enter(this);
			try
			{
				if (this.asyncState == AsyncState.Queued)
				{
					return;
				}
				D.Assert(this.asyncState == AsyncState.Prequeued);
				this.asyncState = AsyncState.Queued;
			}
			finally
			{
				Monitor.Exit(this);
			}
			this.DoWork();
		}
 void OnAsyncStateChange(object sender, GXAsyncWork work, object[] parameters, AsyncState state, string text)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new AsyncStateChangeEventHandler(this.OnAsyncStateChange), sender, work, state, text);
     }
     else
     {
         CancelOperationMenu.Enabled = state == AsyncState.Start;
         if (state == AsyncState.Start)
         {
             StatusLbl.Text = text;
         }
         else if (state == AsyncState.Cancel)
         {
             object target = parameters[0];
             GXDevice device = GXTransactionManager.GetDevice(target);
             if (device != null)
             {
                 device.Cancel();
             }
             //ToolsDisconnectMenu_Click(this, null);
         }
         else if (state == AsyncState.Finish)
         {
             StatusLbl.Text = Gurux.DeviceSuite.Properties.Resources.ReadyTxt;
         }
     }
 }
Exemple #48
0
        /// <summary>Schedules the given action to run asynchronously on the queue when it is available</summary>
        /// <param name="action">The function to run</param>
        /// <returns>A disposable token which you can use to cancel the async action if it has not run yet.
        /// It is always safe to dispose this token, even if the async action has already run</returns>
        public virtual IDisposable DispatchAsync(Action action)
        {
            lock (m_schedulerLock)
            {
                if (m_isDisposed)
                    throw new ObjectDisposedException("SerialQueue", "Cannot call DispatchSync on a disposed queue");

                m_asyncActions.Add(action);
                if (m_asyncState == AsyncState.Idle)
                {
                    // even though we don't hold m_schedulerLock when asyncActionsAreProcessing is set to false
                    // that should be OK as the only "contention" happens up here while we do hold it
                    m_asyncState = AsyncState.Scheduled;
                    m_threadPool.QueueWorkItem(ProcessAsync);
                }
            }

            return new AnonymousDisposable(() => {
                // we can't "take it out" of the threadpool as not all threadpools support that
                lock (m_schedulerLock)
                    m_asyncActions.Remove(action);
            });
        }
Exemple #49
0
        /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary>
        /// <param name="handle">The handle to the file.</param>
        /// <param name="bufferSize">The size of the buffer to use when buffering.</param>
        /// <param name="useAsyncIO">Whether access to the stream is performed asynchronously.</param>
        private void InitFromHandle(SafeFileHandle handle)
        {
            if (_useAsyncIO)
                _asyncState = new AsyncState();

            if (CanSeekCore) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor
                SeekCore(0, SeekOrigin.Current);
        }
Exemple #50
0
 void OnAsyncStateChange(System.Windows.Forms.Control sender, AsyncState state)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new AsyncStateChangeEventHandler(this.OnAsyncStateChange), sender, state);
     }
     else
     {
         CancelBtn.Enabled = state == AsyncState.Start;
         if (state == AsyncState.Cancel)
         {
             DisconnectMnu_Click(this, null);
         }
         ProgressBar.Visible = state == AsyncState.Start;
         if (state == AsyncState.Finish ||
                 state == AsyncState.Cancel)
         {
             StatusLbl.Text = "Ready";
         }
     }
 }
Exemple #51
0
        /// <summary>Internal function which runs on the threadpool to execute the actual async actions</summary>
        protected virtual void ProcessAsync()
        {
            bool schedulerLockTaken = false;
            if (s_queueStack == null)
                s_queueStack = new Stack<IDispatchQueue>();
            s_queueStack.Push(this);
            try
            {
                Monitor.Enter(m_schedulerLock, ref schedulerLockTaken);
                Debug.Assert(schedulerLockTaken);

                m_asyncState = AsyncState.Processing;

                if (m_isDisposed)
                    return; // the actions will have been dumped, there's no point doing anything

                while (m_asyncActions.Count > 0)
                {
                    // get the head of the queue, then release the lock
                    var action = m_asyncActions[0];
                    m_asyncActions.RemoveAt(0);
                    Monitor.Exit(m_schedulerLock);
                    schedulerLockTaken = false;

                    // process the action
                    try
                    {
                        lock(m_executionLock) // we must lock here or a DispatchSync could run concurrently with the last thing in the queue
                            action();
                    }
                    catch (Exception exception)
                    {
                        var handler = UnhandledException;
                        if (handler != null)
                            handler(this, new UnhandledExceptionEventArgs(exception));
                    }

                    // now re-acquire the lock for the next thing
                    Debug.Assert(!schedulerLockTaken);
                    Monitor.Enter(m_schedulerLock, ref schedulerLockTaken);
                    Debug.Assert(schedulerLockTaken);
                }
            }
            finally
            {
                m_asyncState = AsyncState.Idle;
                if (schedulerLockTaken)
                    Monitor.Exit(m_schedulerLock);

                s_queueStack.Pop(); // technically we leak the queue stack threadlocal, but it's probably OK. Windows will free it when the thread exits
            }
        }
Exemple #52
0
        private void OnReceive( IAsyncResult asyncResult )
        {
            Socket s = (Socket)asyncResult.AsyncState;

            try {
                int byteCount = s.EndReceive( asyncResult );

                if ( byteCount > 0 ) {
                    m_NextCheckActivity = DateTime.Now + TimeSpan.FromMinutes( 1.2 );

                    byte[] buffer = m_RecvBuffer;

                    if ( m_Encoder != null )
                        m_Encoder.DecodeIncomingPacket( this, ref buffer, ref byteCount );

                    lock ( m_Buffer )
                        m_Buffer.Enqueue( buffer, 0, byteCount );

                    m_MessagePump.OnReceive( this );

                    lock ( m_AsyncLock ) {
                        m_AsyncState &= ~AsyncState.Pending;

                        if ( ( m_AsyncState & AsyncState.Paused ) == 0 ) {
                            try {
                                InternalBeginReceive();
                            } catch ( Exception ex ) {
                                TraceException( ex );
                                Dispose( false );
                            }
                        }
                    }
                } else {
                    Dispose( false );
                }
            } catch {
                Dispose( false );
            }
        }
        /// <summary>Initializes a stream for reading or writing a Unix file.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="mode">How the file should be opened.</param>
        /// <param name="access">Whether the file will be read, written, or both.</param>
        /// <param name="share">What other access to the file should be allowed.  This is currently ignored.</param>
        /// <param name="bufferSize">The size of the buffer to use when buffering.</param>
        /// <param name="options">Additional options for working with the file.</param>
        internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
            : base(parent)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _path = path;
            _access = access;
            _mode = mode;
            _options = options;
            _bufferLength = bufferSize;
            if ((options & FileOptions.Asynchronous) != 0)
            {
                _useAsyncIO = true;
                _asyncState = new AsyncState();
            }

            // Translate the arguments into arguments for an open call
            Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored
            Interop.Sys.Permissions openPermissions = Interop.Sys.Permissions.S_IRWXU; // creator has read/write/execute permissions; no permissions for anyone else

            // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized.
            _fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions);
            try
            {
                _fileHandle.IsAsync = _useAsyncIO;

                // Lock the file if requested via FileShare.  This is only advisory locking. FileShare.None implies an exclusive 
                // lock on the file and all other modes use a shared lock.  While this is not as granular as Windows, not mandatory, 
                // and not atomic with file opening, it's better than nothing.
                Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH;
                CheckFileCall(Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB));

                // These provide hints around how the file will be accessed.  Specifying both RandomAccess
                // and Sequential together doesn't make sense as they are two competing options on the same spectrum,
                // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided).
                Interop.Sys.FileAdvice fadv =
                    (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM :
                    (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL :
                    0;
                if (fadv != 0)
                {
                    CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), 
                        ignoreNotSupported: true); // just a hint.
                }

                // Jump to the end of the file if opened as Append.
                if (_mode == FileMode.Append)
                {
                    _appendStart = SeekCore(0, SeekOrigin.End);
                }
            }
            catch
            {
                // If anything goes wrong while setting up the stream, make sure we deterministically dispose
                // of the opened handle.
                _fileHandle.Dispose();
                _fileHandle = null;
                throw;
            }
        }
 void IRequestPerformer.Initialize(RequestContext requestContext)
 {
     _requestContext = requestContext;
     _asyncStateObj = new AsyncState();
 }
        /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary>
        /// <param name="handle">The handle to the file.</param>
        /// <param name="access">Whether the file will be read, written, or both.</param>
        /// <param name="bufferSize">The size of the buffer to use when buffering.</param>
        /// <param name="useAsyncIO">Whether access to the stream is performed asynchronously.</param>
        internal UnixFileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool useAsyncIO, FileStream parent)
            : base(parent)
        {
            // Make sure the handle is open
            if (handle.IsInvalid)
                throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));
            if (handle.IsClosed)
                throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed);
            if (access < FileAccess.Read || access > FileAccess.ReadWrite)
                throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
            if (handle.IsAsync.HasValue && useAsyncIO != handle.IsAsync.Value)
                throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle));

            _fileHandle = handle;
            _access = access;
            _exposedHandle = true;
            _bufferLength = bufferSize;
            if (useAsyncIO)
            {
                _useAsyncIO = true;
                _asyncState = new AsyncState();
            }

            if (CanSeek)
            {
                SeekCore(0, SeekOrigin.Current);
            }
        }
Exemple #56
0
		private void Receive_Process( SocketAsyncEventArgs e )
		{
			int byteCount = e.BytesTransferred;

			if ( e.SocketError != SocketError.Success || byteCount <= 0 ) {
				Dispose( false );
				return;
			}

			m_NextCheckActivity = DateTime.Now + TimeSpan.FromMinutes( 1.2 );

			byte[] buffer = m_RecvBuffer;

			if ( m_Encoder != null )
				m_Encoder.DecodeIncomingPacket( this, ref buffer, ref byteCount );

			lock ( m_Buffer )
				m_Buffer.Enqueue( buffer, 0, byteCount );

			m_MessagePump.OnReceive( this );

			lock ( m_AsyncLock ) {
				m_AsyncState &= ~AsyncState.Pending;
			}
		}
Exemple #57
0
 public void populateCommentsBinding(FlatComments binding, string Url)
 {
     AsyncState state = new AsyncState();
     HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
     request.Accept = "application/json"; //atom+xml";
     state.request = request;
     state.binding = binding;
     request.BeginGetResponse(HandleCommentResult, state);
 }
		internal bool PrepareToQueue()
		{
			Monitor.Enter(this);
			bool result;
			try
			{
				if (this.asyncState != AsyncState.Prequeued)
				{
					result = false;
				}
				else
				{
					this.asyncState = AsyncState.Queued;
					result = true;
				}
			}
			finally
			{
				Monitor.Exit(this);
			}
			return result;
		}
        /// <summary>Initializes a stream for reading or writing a Unix file.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="mode">How the file should be opened.</param>
        /// <param name="access">Whether the file will be read, written, or both.</param>
        /// <param name="share">What other access to the file should be allowed.  This is currently ignored.</param>
        /// <param name="bufferSize">The size of the buffer to use when buffering.</param>
        /// <param name="options">Additional options for working with the file.</param>
        internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
            : base(parent)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _path = path;
            _access = access;
            _mode = mode;
            _options = options;
            _bufferLength = bufferSize;
            if ((options & FileOptions.Asynchronous) != 0)
            {
                _useAsyncIO = true;
                _asyncState = new AsyncState();
            }

            // Translate the arguments into arguments for an open call.
            Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored

            // If the file gets created a new, we'll select the permissions for it.  Most utilities by default use 666 (read and 
            // write for all). However, on Windows it's possible to write out a file and then execute it.  To maintain that similarity, 
            // we use 766, so that in addition the user has execute privileges. No matter what we choose, it'll be subject to the umask 
            // applied by the system, such that the actual permissions will typically be less than what we select here.
            const Interop.Sys.Permissions openPermissions =
                Interop.Sys.Permissions.S_IRWXU |
                Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP |
                Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH;

            // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized.
            _fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions);
            try
            {
                _fileHandle.IsAsync = _useAsyncIO;

                // Lock the file if requested via FileShare.  This is only advisory locking. FileShare.None implies an exclusive 
                // lock on the file and all other modes use a shared lock.  While this is not as granular as Windows, not mandatory, 
                // and not atomic with file opening, it's better than nothing.  Some kinds of files, e.g. FIFOs, don't support
                // locking on some platforms, e.g. OSX, and so if flock returns ENOTSUP, we similarly treat it as a hint and ignore it,
                // as we don't want to entirely prevent usage of a particular file simply because locking isn't supported.
                Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH;
                CheckFileCall(Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB), ignoreNotSupported: true);

                // These provide hints around how the file will be accessed.  Specifying both RandomAccess
                // and Sequential together doesn't make sense as they are two competing options on the same spectrum,
                // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided).
                Interop.Sys.FileAdvice fadv =
                    (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM :
                    (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL :
                    0;
                if (fadv != 0)
                {
                    CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), 
                        ignoreNotSupported: true); // just a hint.
                }

                // Jump to the end of the file if opened as Append.
                if (_mode == FileMode.Append)
                {
                    _appendStart = SeekCore(0, SeekOrigin.End);
                }
            }
            catch
            {
                // If anything goes wrong while setting up the stream, make sure we deterministically dispose
                // of the opened handle.
                _fileHandle.Dispose();
                _fileHandle = null;
                throw;
            }
        }
Exemple #60
0
 void OnAsyncStateChange(System.Windows.Forms.Control sender, AsyncState state)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new AsyncStateChangeEventHandler(this.OnAsyncStateChange), sender, state);
     }
     else
     {
         CancelBtn.Enabled = state == AsyncState.Start;
         if (state == AsyncState.Cancel)
         {
             DisconnectMnu_Click(this, null);
         }
     }
 }