|
6541
|
Programación / .NET (C#, VB.NET, ASP) / Re: Problema con modificación de un PictureBox desde el hilo generado por un Timer.
|
en: 6 Octubre 2014, 16:21 pm
|
Como he comentado en otras ocasiones C++/Cli no es mi fuerte, quizás me equivoque en algún aspecto de lo que voy a comentar a continuación, pero he notado cierta irregularidad aquí: FileStream ^fs = gcnew FileStream(path, FileMode::Open, FileAccess::Read); BinaryReader ^br = gcnew BinaryReader(fs);
Me he fijado en el operador gcnew, y me he informado un poco sobre su funcionalidad, pero al parecer dicho operador lo único que hace es indicar que los objetos se deben auto liberar, eso no significa que se vayan a liberar inmediatamente despues de enviar el return value, el garbage collector libera recursos cuando así lo cree necesario (a menos que lo invoques directamente), puede ser inmediatamente, o pueden pasar 2 o 20 segundos, aunque, con el uso de ese operador no estoy nada seguro la verdad, pero prueba a añadirle un bloque Finally a tu Try/catch para liberar los objetos: Dim fs As FileStream = Nothing Dim br As BinaryReader = Nothing Try fs = New FileStream("", FileMode.Open, FileAccess.Read) br = New BinaryReader(fs) Catch ex As Exception Finally If fs IsNot Nothing Then fs.Close() End If If br IsNot Nothing Then br.Close() End If End Try
C# (conversión al vuelo): FileStream fs = null; BinaryReader br = null; try { fs = new FileStream ("", FileMode .Open, FileAccess .Read); br = new BinaryReader (fs ); } catch (Exception ex) { } finally { if (fs != null) { fs.Close(); } if (br != null) { br.Close(); } }
Lo mismo digo en el bloque Try/Catch donde usas el método LockBits, ¿que ocurre si hubiera un error de por medio y no se procesa la instrucción UnLockBits?, yo directamente eliminaría el Try/catch, y en caso de encontrar una excepción la intentaría resolver, pero bueno, si quieres usar Try/catch entonces es tu deber asegurarte de que la imagen se desbloquea siempre en cualquier circunstancia: Dim bmpData As BitmapData = Nothing Dim bmp As Bitmap = Nothing Dim success As Boolean = False Try bmp = Bitmap.FromFile("") bmpData = bmp.LockBits(New Rectangle With {.Width = bmp.Width, .Height = bmp.Height}, ImageLockMode.ReadWrite, bmp.PixelFormat) bmp.UnlockBits(bmpData) success = True Catch ex As Exception Finally If Not success Then bmp.UnlockBits(bmpData) End If End Try
C# (conversión al vuelo): BitmapData bmpData = null; Bitmap bmp = null; bool success = false; try { bmp = Bitmap.FromFile(""); bmpData = bmp .LockBits(new Rectangle { Width = bmp.Width, Height = bmp.Height }, ImageLockMode.ReadWrite, bmp.PixelFormat); bmp.UnlockBits(bmpData); success = true; } catch (Exception ex) { } finally { if (!success) { bmp.UnlockBits(bmpData); } }
No se si esos pequeños ajustes resolverán el problema, pero tampoco puedo ayudar mucho más. Saludos!
|
|
|
6543
|
Programación / .NET (C#, VB.NET, ASP) / Re: Problema con modificación de un PictureBox desde el hilo generado por un Timer.
|
en: 6 Octubre 2014, 00:48 am
|
El mensaje de error se explica por si mismo, te está indicando que se está intentando bloquear la misma imagen simultaneamente ( Bitmap.LockBits) sin haberla desbloqueado previamente ( Bitmap.UnlockBits), y claro está, no puedes bloquear la imagen dos veces consecutivas si no la desbloqueas, comprueba bien lo que estés haciendo con ese objeto ' bitMap'. EDITO: Tras leer el título de tu pregunta (que antes no me fijé muy bien) afirmas que la aplicación es multi-hilo, entonces probablemente la causa se deba a que varios hilos están intentando acceder/usar la misma imagen simultaneamente, el problema sigue siendo el mismo que he mencionado arriba. Prueba a utilizar el método Bitmap.Clone para evitar esa excepción. ⇲
3 - He leído algo de Invoke e InvokeRequired. PictureBox tiene el InvokeRequired a 'false' así que imagino que no tiene nada que ver con usar invoke. Si tu aplicación es single-threaded no tienes porque preocuparte desde que Class (Form) asignes la propiedad de cualquier control, de lo contrario, si tu aplicación es multi-htreaded y estás intentando modificar la propiedad de ese control desde un thread distinto al que creó el control, entonces por supuestisimo debes usar Control.InvokeRequired + Control.Invoke. Aparte, en lo referente al Timer, no veo razón para que te estés complicando la vida con un Threading.Timer (+ Callbacks), el cual si tu aplicación es multi-hilo entonces es probable que también cause un error derivado con la imagen, ¿es realmente necesario para tu propósito?, prueba a utilizar un Windows.Forms.timer en su lugar. saludos
|
|
|
6544
|
Programación / .NET (C#, VB.NET, ASP) / Re: Descifrar operaciones en resultados correlativos
|
en: 5 Octubre 2014, 19:33 pm
|
Bueno no se que ha pasado que no entraba el foro,me imagino que una caida de servidor Gracias elektro lo revizo Luis Dímelo a mi, a los 10 minutos de leer tu pregunta (ayer sabado por la noche) ya habia escrito el ejemplo de arriba para ti y te lo quería mostrar para que tuvieras algo con lo que programar ' por que era sábado' como dijiste , pero hasta hoy por la mañana no pude postear el code xD. PD: Todo es por culpa de un individuo o una panda de Juanckers que se dedican a Ddosear el foro, pero bueno, en este mundo debemos aprender a convivir con gente (y gentuza) de todo tipo.Saludos!
|
|
|
6546
|
Programación / .NET (C#, VB.NET, ASP) / Re: Descifrar operaciones en resultados correlativos
|
en: 5 Octubre 2014, 09:58 am
|
Solo tienes que obtener la diferencia, no se que tipo de complicación le encuentras para realizar lo mismo en un código. Prueba así: Public Class Form1 Private Shadows Sub Load() Handles MyBase.Load Dim sb As New System.Text.StringBuilder Dim Values As New List(Of Integer()) From { ({1I, 19, 1I}), ({7I, 22, 4I}), ({8I, 27, 11}), ({20, 29, 17}), ({23, 33, 22}), ({39, 46, 31}) } For Each ValueCol() As Integer In Values Dim Value1 As Integer = ValueCol(0) Dim Value2 As Integer = ValueCol(1) Dim Value3 As Integer = ValueCol(2) Dim Diff1 As String = GetDifferenceExpression(Value1, Value2) Dim Diff2 As String = GetDifferenceExpression(Value2, Value3) sb.AppendLine(String.Format("{0} -> {1} = {2}", Value1.ToString("00"), Value2.ToString("00"), Diff1)) sb.AppendLine(String.Format("{0} -> {1} = {2}", Value2.ToString("00"), Value3.ToString("00"), Diff2)) sb.AppendLine() Next ValueCol MessageBox.Show(sb.ToString) Application.Exit() End Sub ' Get Difference expression ' ( By Elektro ) ' ' Usage Examples: ' MessageBox.Show(GetDifferenceExpression(5, 10)) ' ''' <summary> ''' Gets the arithmetic sum/rest difference expression between two values. ''' </summary> ''' <param name="Value1">The first value.</param> ''' <param name="Value2">The second value.</param> ''' <returns>The arithmetic expression.</returns> Friend Function GetDifferenceExpression(ByVal Value1 As Long, ByVal Value2 As Long) As String Select Case Value2 Case Is > Value1 ' Value2 is bigger than Value1. Return String.Format("+{0}", CStr(Value2 - Value1)) Case Is < Value1 ' Value2 is lower than Value1. Return String.Format("-{0}", CStr(Value1 - Value2)) Case Else ' Value2 is equals to Value1. Return "0" End Select End Function End Class
Saludos.
|
|
|
6549
|
Sistemas Operativos / Windows / Re: Procesos y subprocesos windows 8
|
en: 4 Octubre 2014, 22:17 pm
|
por cierto
¿te parece mucho que mi sistema coja un 30%-45% de memoria ram? Es que, sinceramente, haces una pregunta sobre tu PC sin dar información de tu PC. ¿como pretendes que te digamos si el consumo es mucho o poco si no especificas cuanta ram tienes instalada (eso, como mínimo)?, o el navegador que utilizas para ver videos de youtube, ya que por ejemplo el Firefox consume mucha, muchíiiiisima Ram cuando el plugincontainer entrá en acción, en fin, detalles que ayuden a diagnosticar un posible problema en tu PC, porque es absurdo decirte si lo considero mucho o poco consumo sin conocer esos y otros detalles, como los procesos que tienes en ejecución. De todas formas en el administrador de tareas puedes hacerte una idea de lo que consume cada proceso, y con cualquier buen profiler puedes realizar un análisis/diagnostico de cualquier proceso para averiguar la RAM (la real) que está consumiendo proceso por proceso en cada momento, para averiguar posibles fugas de memoria en las aplicaciones. Como profiler te recomendaría el de Telerik (JustTrace) pero creo que solo soporta aplicaciónes .NET, y el de JetBrains (dotMemory) también, así que no se decirte un profiler de uso general xD. Saludos!
|
|
|
6550
|
Programación / .NET (C#, VB.NET, ASP) / Re: ¿Alternativa al atributo RangeAttribute de ASP.NET?
|
en: 4 Octubre 2014, 20:31 pm
|
Vaya, me alegra verte por aqui de nuevo NovLucker, y muchas gracias por la documentación, aunque no he sacado practicamente nada en claro. Mi intención es transformar esto: Public Class MyType ''' <summary> ''' Gets or sets the value. ''' </summary> ''' <value>The value.</value> Public Property MyProperty As Integer Get Return Me._MyValue End Get Set(ByVal value As Integer) If value < Me._MyValueMin Then If Me._MyValueThrowRangeException Then Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage) End If Me._MyValue = Me._MyValueMin ElseIf value > Me._MyValueMax Then If Me._MyValueThrowRangeException Then Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage) End If Me._MyValue = Me._MyValueMax Else Me._MyValue = value End If End Set End Property Private _MyValue As Integer = 0I Private _MyValueMin As Integer = 0I Private _MyValueMax As Integer = 10I Private _MyValueThrowRangeException As Boolean = True Private _MyValueExceptionMessage As String = String.Format("The valid range is beetwen {0} and {1}", Me._MyValueMin, Me._MyValueMax) End Class
En algo más simplificado, y sobre todo rehusable, como esto: Public NotInheritable Class MyType ''' <summary> ''' Gets or sets the value. ''' Valid range is between 0 and 10. ''' </summary> ''' <value>The value.</value> <RangeAttribute(0, 10, ThrowRangeException:=False, ExceptionMessage:="")> Public Property MyProperty As Integer End Class
Pero no soy capaz de descubrir o entender como puedo hookear el getter/setter, apenas tengo información sobre ello, de todas formas intenté empezar a hacerlo y esto es lo que tengo, un código que no sirve para nada, porque no estoy evaluando nada, pero al menos sirve como idea inicial: <AttributeUsage(AttributeTargets.Property, AllowMultiple:=False)> Public Class RangeAttribute : Inherits Attribute ''' <summary> ''' Indicates the Minimum range value. ''' </summary> Public Minimum As Single ''' <summary> ''' Indicates the Maximum range value. ''' </summary> Public Maximum As Single ''' <summary> ''' Determines whether to throw an exception when the value is not in range. ''' </summary> Public ThrowRangeException As Boolean ''' <summary> ''' Indicates the exception message to show when the value is not in range. ''' </summary> Public ExceptionMessage As String ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class. ''' </summary> ''' <param name="Minimum">The minimum range value.</param> ''' <param name="Maximum">The maximum range value.</param> Public Sub New(ByVal Minimum As Single, ByVal Maximum As Single) Me.New(Minimum, Maximum, ThrowRangeException:=False, ExceptionMessage:=String.Empty) End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class. ''' </summary> ''' <param name="Minimum">The minimum range value.</param> ''' <param name="Maximum">The maximum range value.</param> ''' <param name="ThrowRangeException"> ''' Determines whether to throw an exception when the value is not in range. ''' </param> Public Sub New(ByVal Minimum As Single, ByVal Maximum As Single, ByVal ThrowRangeException As Boolean, Optional ByVal ExceptionMessage As String = "") Me.Minimum = Minimum Me.Maximum = Maximum Me.ThrowRangeException = ThrowRangeException If Not String.IsNullOrEmpty(ExceptionMessage) Then Me.ExceptionMessage = ExceptionMessage Else Me.ExceptionMessage = String.Format("The valid range is beetwen {0} and {1}", Minimum, Maximum) End If End Sub End Class
Cualquier información adicional se agradece. Un saludo!
|
|
|
|
|
|
|