Memory Access Violation disposing libvlcsharp objects from a task - object

Link to full sample app
C# Winform application built in Visual Studio 2019 libvlcsharp runtime version v4.0.30319 version 3.4.4.0
I built a simpler application that has the same problem as one that is currently deployed.
Here's where the code gets the player started:
videoView1.MediaPlayer.Play(new Media(_libVLC, URI,FromType.FromLocation));
Here's the cleanup code snip:
videoView1.MediaPlayer.Stop();
videoView1.MediaPlayer.Dispose();
videoView1.Dispose();
//dispose glibvlc at higher level
The MediaPlayer dispose works OK no errors. However, videoview dispose causes a Memory Access Violation. I know this isn't normal because I built a simple c# application without using a task to dispose and clean up the objects and that worked just fine.
However the application I'm trying to debug has one thread per stream that is being displayed to manage setting up and shutting down each connection.
If the code just calls dispose on the mediaplayer and does not dispose the videoview object then the object that contains the libvlcsharp objects causes a Memory Access Violation when it gets disposed.
If I don't dispose of the MediaPlayer object any subsequent object dispose calls work OK.
I have verified that this leaks memory.
In UI class
Setup all the form variables.
instantiate LibVLC
StartVideo(); This ends with the Play method
Task.Run(() => Ask()); This emulates what may be happening in the
real app
The Ask function asks if the user wants to exit the program or kill the current player and build and start it again.
if user cancels it exits through the On Application Exit handler which
does executes the Dispose sequence shown above. This works as designed.
If user kills and restarts then it fails on the videoView1 dispose as
described above.
Here's the c# sample ask function.
public void Ask()
{
while (true)
{
DialogResult r = MessageBox.Show("Dispose and Start Again?", "Memory Access Violation Test", MessageBoxButtons.OKCancel);
if (r == DialogResult.OK)
{
videoView1.MediaPlayer.Stop();
videoView1.MediaPlayer.Dispose();
videoView1.Dispose();
StartVideo();
}
else
{
Invoke(new Action(() => this.Close()));
}
}
}

To fix problem upgrade to version 3.6.1.0 for both libvlcsharp and libvlcwinforms.winforms

Related

Coded UI in VS2013 closes the application automatically once test method is completed running

In visual studio 2013, coded ui closes the application automatically once all test method completed running.
[TestInitialize]
public void TestInitialize()
{
uiCommonEE = UICommonEE.GetCommonEE();
}
[TestCleanup]
public void TestCleanup()
{
}
[TestMethod]
public void OpenWorkspaceTest()
{
uiCommonEE.SetBaseState();
uiCommonEE.OpenWorkspace("C:\Path\EE_Multmodule_AllDataTypes.eew");
}
I'm launching my application from TestInitialize() Method
once the testmethod is completed running, application gets closed automatically.
In testcleanuup() and classcleanup() method I haven't written anything.
I want application to be still running once all the test method of the codedUI are completed running.
Thanks in advance
You can use CloseOnPlayback on the ApplicationUnderTest or BrowserWindow class, but this will only keep the application open during the test run. The moment all test methods in the test class have been executed the playback engine will still cleanup any instance created during the test. So between all test methods in the test class the application will be kept open, when all tests completed everything will be cleaned up.
Run the application from the [ClassInitialize] or the [AssemblyInitialize] methods, but do not use Coded UI's methods to start it. This is because Coded UI keeps track of started applications so it can close them at the end of the test run. Instead use one of the other Windows process start methods, the ProcessStartInfo and Process classes, see here, may be suitable.
The question does not say what should happen if the tests are started when the application is already running. So perhaps the [ClassInitialize] or the [AssemblyInitialize] method should check whether the application is already active before running it, or perhaps the application should ignore or reject attempts to start it when it is already running.

Closing Netty server cleanly

Hello currently I am developing an Arquillian extension for Moco framework (https://github.com/dreamhead/moco). Moco is used for testing RESTful services and relies on Netty for dealing with communication. Currently Moco is using Netty 4.0.18.Final.
But I have found a problem when running Moco (and Netty server) inside a container (Arquillian runs tests within the container) and is that it starts correctly but when the application is undeployed and server is shutdown next log error messages are printed:
SEVERE: The web application [/ba32e781-3a18-44b3-9547-7c26787f3fe7] appears to have started a thread named [pool-2-thread-1] but has failed to stop it. This is very likely to create a memory leak.
abr 08, 2014 10:29:06 AM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/ba32e781-3a18-44b3-9547-7c26787f3fe7] created a ThreadLocal with key of type [io.netty.util.internal.ThreadLocalRandom$2] (value [io.netty.util.internal.ThreadLocalRandom$2#77468cae]) and a value of type [io.netty.util.internal.ThreadLocalRandom] (value [io.netty.util.internal.ThreadLocalRandom#6cd3851]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Basically it seems that there are some threads that are not closed yet when the server tries to shutdown.
From the point of view of Arquillian extension when the application is deployed into the server the start method of Moco is called and before undeploying the application the stop method from Moco is called.
But let me show you the code of Moco:
public int start(final int port, ChannelHandler pipelineFactory) {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(pipelineFactory);
try {
future = bootstrap.bind(port).sync();
SocketAddress socketAddress = future.channel().localAddress();
address = (InetSocketAddress) socketAddress;
return address.getPort();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
and the stop method looks like:
private void doStop() {
if (future != null) {
future.channel().close().syncUninterruptibly();
future = null;
}
So it seems that the close method returns before killing all the threads and for this reason containers warns you about possible memory leaks.
Because I have never used Netty I was wondering if there is a way to ensure that the whole Netty runtime is closed.
Thank you so much for your help.
I am new to Netty as well (and unfamiliar with Arquillian), but based on the Netty Docs examples I believe you might not be shutting down the EventLoopGroups you created (bossGroup, workerGroup). From the Netty 4.0 User Guide:
Shutting down a Netty application is usually as simple as shutting down all EventLoopGroups you created via shutdownGracefully(). It returns a Future that notifies you when the EventLoopGroup has been terminated completely and all Channels that belong to the group have been closed.
So your doStop() method might look like:
private void doStop() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
An example in the Netty docs: Http Static File Server Example

Leap Listener controller stops working after some time in VS2012

We have integrated flash game (crazytaxi.swf) inside Windows form application in VS Express 2012 for Windows Desktop.We are controlling game with the help of gestures using leapmotion controller.
What happens is when we run project in VS2012,game starts normally.We play game using gesture (left,right etc.).But after some time controller stops listening by exiting its thread.We can see that in output window.
"The thread '' (0x1b50) has exited with code 0 (0x0)." this we get in output window.
We are not getting how to overcome this challenge.
You didn't provide enough information but from what I gather, your LEAP thread ran to completion and closed. This can occur if you declare and initialize your listener and controller variables in a function and the variables go out of scope when the function is executed. This causes Garbage Collector to dispose both controller and listener at what might seemingly appear as random (non reproductable) moments. To fix this issue, create a singleton for the controller and listener - this can boil down to simply defining a static controller and listener variables in some class. This way the listener and controller objects will never go out of scope and get disposed by the GC.
"The thread '' (0x1b50) has exited with code 0 (0x0) basically says that:
The thread with the ID 6992 ran and completed the operation successfully.
System Error Codes (0-499)
The question is, does the device stop tracking?
Here are my 0x0's from my Leap Motion app (its working fine):
The thread 'vshost.NotifyLoad' (0x364) has exited with code 0 (0x0).
The thread '' (0x3348) has exited with code 0 (0x0).
The thread 'vshost.LoadReference' (0x37c8) has exited with code 0 (0x0).
Also, on a side note, because it has nothing to do with the error code - are you removing the listener from the controller, and then disposing of them both when the application is being closed? Not properly disposing of objects will cause problems.
A second note - onExit and onDisconnet are two different things.
onDisconnect(controller:Controller):void
Called when the Controller object disconnects from the Leap Motion software.
Listener
onExit(controller:Controller):void
Called when this Listener object is removed from the Controller or the Controller instance is destroyed.
In case somebody is having similar problems here is the reply I sent over email after having a look at the code:
I've looked at the code, since you only sent me a few files I had to comment out the the references to classes that was not included in the zip.
The code runs fine with 3 different Leap Motion devices - when I comment out from the method, what I suggest is:
Update the SDK. I used .Net 4 dll and the latest version of the SDK which today is: v.1.0.8.7665
Dispose the objects once you are done using them. Dispose Frames after using them, Remove listener from the Controller, and dispose Controller when the device isn't used anymore or the application is being closed.
I noticed some Timers and DispatcherTimers they were being created, but I couldn't find any references to where they were being used. What are these being used for? DispatcherTimer doesn't belong in a windows forms application.
My best guess - and I hate to guess - is that there is a threading problem OR that the objects aren't being disposed correctly - OR you are using an SDK version that had bugs.
I have two applications on GitHub - feel free to use the code as you want. There is one for WPF and one for Windows Forms - both need to be updated for latest SDK as some things have been deprecated (such as the Screen class) in later versions of the SDK.
WPF:
https://github.com/IrisClasson/Leap-Motion
Windows Forms:
https://github.com/IrisClasson/LeapMotion_WinForms_Demo_OLD_SDK
Disclaimer: I don't do much, if any WinForms development
I had a same issue with my WPF application and Leap Motion code but the code works fine with a console application.
In WPF when I globally declared the Leap-Listener and the controller Object, I did not face the error any more and the Listener is active all time.
Just declare the listener and controller in the class (globally) from which you call the listener
public static LeapListener listener;
public static Controller controller;
Now use this listener object, and add it to the controller and enable gesture property of the controller in a function or a constructor.
listener = new LeapListener();
controller.AddListener(listener);
controller = new Controller();
This should solve the issue. If the problem still persists (detection problem), simply initialize and add the same listener object to the controller object onExit event. Now the gesture and other properties exist as you are not creating a new instance of the controller again.

Calling WCF Service Operation in multithreaded Console Application

I have below application:
Its windows console .NET 3.0 application
I'm creating 20 workloads and assigning them to threadpool to process.
Each thread in ThreadPool creates WCF Client and calls service with request created using workload assigned.
Sometimes on production servers[12 core machines], I get following exception:
There was an error reflecting type 'xyz' while invoking operation using WCF client. This starts appearing in all threads. After sometime it suddenly disappears and starts appearing again.
Code:
Pseudo Code:
for(int i=0;i<20;i++)
{
MultiThreadedProcess proc =new MultThreadedProcess(someData[i]);
ThreadPool.QueueUserWorkItem(proc.CallBack,i);
}
In Class MultiThreadedProcess, I do something like this:
public void Callback(object index)
{
MyServiceClient client = new MyServiceClient();
MyServiceResponse response =client.SomeOperation(new MyServiceRequest(proc.SomeData));
client.close();
//Process Response
}
Can anyone suggest some resolutions for this problem?
If you can turn on diagnostic, appears to me serialization issue, there might be chance that certain data members/values are not able to de-serialized properly for operation call.

Silverlight 4 Ria Services and multiple threads

I have a very long running query that takes too long to keep my client connected. I want to make a call into my DomainService, create a new worker thread, then return from the service so that my client can then begin polling to see if the long running query is complete.
The problem I am running into is that since my calling thread is exiting right away, I am getting exceptions thrown when my worker tries to access any entities since the ObjectContext gets disposed when the original thread ends.
Here is how I create the new context and call from my Silverlight client:
MyDomainContext context = new MyDomainContext();
context.SearchAndStore(_myParm, SearchQuery,
p => {
if (p.HasError) { // Do some work and return to start
} // polling the server for completion...
}, null);
The entry method on the server:
[Invoke]
public int SearchAndStore(object parm)
{
Thread t = new Thread(new ParameterizedThreadStart(SearchThread));
t.Start(parms);
return 0;
// Once this method returns, I get ObjectContext already Disposed Exceptions
}
Here is the WorkerProc method that gets called with the new Thread. As soon as I try to iterate through my query1 object, I get the ObjectContext already Disposed exception.
private void WorkerProc(object o)
{
HashSet<long> excludeList = new HashSet<long>();
var query1 = from doc in this.ObjectContext.Documents
join filters in this.ObjectContext.AppliedGlobalFilters
.Where(f => f.FilterId == 1)
on doc.FileExtension equals filters.FilterValue
select doc.FileId;
foreach (long fileId in query1) // Here occurs the exception because the
{ // Object Context is already disposed of.
excludeList.Add(fileId);
}
}
How can I prevent this from happening? Is there a way to create a new context for the new thread? I'm really stuck on this one.
Thanks.
Since you're using WCF RIA. I have to assume that you're implementing two parts:
A WCF Web Service
A Silverlight client which consumes the WCF Service.
So, this means that you have two applications. The service running on IIS, and the Silverlight running on the web browser. These applications have different life cycles.
The silverlight application starts living when it's loaded in the web page, and it dies when the page is closed (or an exception happens). On the other hand (at server side), the WCF Web Service life is quite sort. You application starts living when the service is requested and it dies once the request has finished.
In your case your the server request finishes when the SearchAndStore method finishes. Thus, when this particular method starts ,you create an Thread which starts running on background (in the server), and your method continues the execution, which is more likely to finishes in a couple of lines.
If I'm right, you don't need to do this. You can call your method without using a thread, in theory it does not matter if it takes awhile to respond. this is because the Silvelight application (on the client) won't be waiting. In Silverlight all the operations are asynchronous (this means that they're running in their own thread). Therefore, when you call the service method from the client, you only have to wait until the callback is invoked.
If it's really taking long time, you are more likely to look for a mechanism to keep the connection between your silverlight client and your web server alive for longer. I think by modifying the service configuration.
Here is a sample of what I'm saying:
https://github.com/hmadrigal/CodeSamples/tree/master/wcfria/SampleWebApplication01
In the sample you can see the different times on client and server side. You click the button and have to wait 30 seconds to receive a response from the server.
I hope this helps,
Best regards,
Herber

Resources