AForge.Video.JPEGStream.WorkerThread C# (CSharp) Method

WorkerThread() private method

private WorkerThread ( ) : void
return void
        private void WorkerThread( )
		{
            // buffer to read stream
			byte[] buffer = new byte[bufferSize];
            // HTTP web request
			HttpWebRequest request = null;
            // web responce
			WebResponse response = null;
            // stream for JPEG downloading
			Stream stream = null;
            // random generator to add fake parameter for cache preventing
			Random rand = new Random( (int) DateTime.Now.Ticks );
            // download start time and duration
			DateTime start;
			TimeSpan span;

            while ( !stopEvent.WaitOne( 0, false ) )
			{
				int	read, total = 0;

				try
				{
                    // set dowbload start time
					start = DateTime.Now;

					// create request
					if ( !preventCaching )
					{
                        // request without cache prevention
                        request = (HttpWebRequest) WebRequest.Create( source );
					}
					else
					{
                        // request with cache prevention
                        request = (HttpWebRequest) WebRequest.Create( source + ( ( source.IndexOf( '?' ) == -1 ) ? '?' : '&' ) + "fake=" + rand.Next( ).ToString( ) );
					}

                    // set proxy
                    if ( proxy != null )
                    {
                        request.Proxy = proxy;
                    }

                    // set timeout value for the request
                    request.Timeout = requestTimeout;
					// set login and password
					if ( ( login != null ) && ( password != null ) && ( login != string.Empty ) )
                        request.Credentials = new NetworkCredential( login, password );
					// set connection group name
					if ( useSeparateConnectionGroup )
                        request.ConnectionGroupName = GetHashCode( ).ToString( );
                    // force basic authentication through extra headers if required
                    if ( forceBasicAuthentication )
                    {
                        string authInfo = string.Format( "{0}:{1}", login, password );
                        authInfo = Convert.ToBase64String( Encoding.Default.GetBytes( authInfo ) );
                        request.Headers["Authorization"] = "Basic " + authInfo;
                    }
					// get response
                    response = request.GetResponse( );
					// get response stream
                    stream = response.GetResponseStream( );
                    stream.ReadTimeout = requestTimeout;

					// loop
					while ( !stopEvent.WaitOne( 0, false ) )
					{
						// check total read
						if ( total > bufferSize - readSize )
						{
							total = 0;
						}

						// read next portion from stream
						if ( ( read = stream.Read( buffer, total, readSize ) ) == 0 )
							break;

						total += read;

						// increment received bytes counter
						bytesReceived += read;
					}

					if ( !stopEvent.WaitOne( 0, false ) )
					{
						// increment frames counter
						framesReceived++;

						// provide new image to clients
						if ( NewFrame != null )
						{
							System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(new MemoryStream(buffer, 0, total));
							// notify client
                            NewFrame( this, new NewFrameEventArgs( bitmap ) );
							// release the image
                            bitmap.Dispose( );
                            bitmap = null;
						}
					}

					// wait for a while ?
					if ( frameInterval > 0 )
					{
						// get download duration
						span = DateTime.Now.Subtract( start );
						// miliseconds to sleep
						int msec = frameInterval - (int) span.TotalMilliseconds;

                        if ( ( msec > 0 ) && ( stopEvent.WaitOne( msec, false ) ) )
                            break;
					}
				}
                catch ( ThreadAbortException )
                {
                    break;
                }
                catch ( Exception exception )
				{
                    // provide information to clients
                    if ( VideoSourceError != null )
                    {
                        VideoSourceError( this, new VideoSourceErrorEventArgs( exception.Message ) );
                    }
                    // wait for a while before the next try
                    Thread.Sleep( 250 );
                }
				finally
				{
					// abort request
					if ( request != null)
					{
                        request.Abort( );
                        request = null;
					}
					// close response stream
					if ( stream != null )
					{
						stream.Close( );
						stream = null;
					}
					// close response
					if ( response != null )
					{
                        response.Close( );
                        response = null;
					}
				}

				// need to stop ?
				if ( stopEvent.WaitOne( 0, false ) )
					break;
			}

            if ( PlayingFinished != null )
            {
                PlayingFinished( this, ReasonToFinishPlaying.StoppedByUser );
            }
		}
	}