Coder Social home page Coder Social logo

soheilkd / singleinstancecore Goto Github PK

View Code? Open in Web Editor NEW
33.0 5.0 2.0 38 KB

For developing single instance application - For Windows applications on .NET Core/ .NET 5

License: MIT License

C# 100.00%
single-instance single-instance-app windows windows-desktop windows-forms wpf

singleinstancecore's People

Contributors

nikeee avatar soheilkd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

u-c-s ruekov

singleinstancecore's Issues

WinForms Usage

Awesome library!

I'm trying to get it to work with WinForms.

This is my current attempt:

static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var app = new TestApplication();

        var isFirstInstance = app.InitializeAsFirstInstance("Test");
        if (isFirstInstance)
        {
            try
            {
                app.Run();
            }
            finally
            {
                SingleInstance.Cleanup();
            }
        }
    }
}

class TestApplication : ISingleInstance
{
    public void Run()
    {
        Application.SetHighDpiMode(HighDpiMode.SystemAware);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }

    public void OnInstanceInvoked(string[] args)
    {
        MessageBox.Show("OnInstanceInvoked");
        throw new NotImplementedException();
    }
}

Observation:

  • There is only one instance created
  • OnInstanceInvoked is not invoked on any instance
  • Application.Run(new MainForm()) blocks until the main form is closed
  • In the second instance, InitializeAsFirstInstance returns false, as expected

What am I doing wrong?

If we get this to work, I'd like create a PR to put a WinForms sample in the README.

License

Hello! I am using this in something I plan to use the MIT License for, would you mind adding the same license to SingleInstanceCore?

Thanks in advance.

Subsequent instances crash when started together

Hi,

I've come across a scenario where subsequent instances crash with the following error:

System.TimeoutException: Gave up waiting for read lock
   at TinyIpc.Synchronization.TinyReadWriteLock.AcquireReadLock() in /_/src/TinyIpc/Synchronization/TinyReadWriteLock.cs:line 130
   at TinyIpc.IO.TinyMemoryMappedFile.Read() in /_/src/TinyIpc/IO/TinyMemoryMappedFile.cs:line 158
   at TinyIpc.Messaging.TinyMessageBus..ctor(ITinyMemoryMappedFile memoryMappedFile, Boolean disposeFile, TimeSpan minMessageAge) in /_/src/TinyIpc/Messaging/TinyMessageBus.cs:line 111
   at TinyIpc.Messaging.TinyMessageBus..ctor(ITinyMemoryMappedFile memoryMappedFile, Boolean disposeFile) in /_/src/TinyIpc/Messaging/TinyMessageBus.cs:line 90
   at TinyIpc.Messaging.TinyMessageBus..ctor(String name) in /_/src/TinyIpc/Messaging/TinyMessageBus.cs:line 63
   at SingleInstanceCore.SingleInstance.SignalFirstInstance(String channelName, IList`1 commandLineArgs)
   at SingleInstanceCore.SingleInstance.InitializeAsFirstInstance[T](T instance, String uniqueName)

This happens when multiple files are selected and opened from Windows File Explorer, each file starting an instance of my application and then all these instances end up trying to signal the first instance at the same time. I've worked around this in my code by setting up a named Mutex that only allows one instance at a time calling InitializeAsFirstInstance:

using (var mutex = new Mutex(false, uniqueAppName))
{
    try { mutex.WaitOne(3000); } catch (AbandonedMutexException) { }
                
    try
    {
       if (!this.InitializeAsFirstInstance(uniqueAppName))
           Environment.Exit(0);
    }
    finally
    {
        mutex.ReleaseMutex();
    }
}

This works, but it would probably be better if SingleInstanceCore handled this internally, inside the SingleInstance.SignalFirstInstance method.

Thanks for making this library available!

.NET 5 compatibility

Does this library also work with .NET 5/6?

Is it possible to use it with WinForms?

Not an issue, just thanks!

Thanks mate, this works like a charm.

Just a small typo, change:
bool isFirstInstance = SingleInstance.InitializeAsFirstInstance("soheilkd_EPlayerIPC"))
to:
bool isFirstInstance = SingleInstance.InitializeAsFirstInstance("soheilkd_EPlayerIPC");
in the README (change the ) to a ;)

Application closes before CommandLineArgs get sent

We're having a problem where OnInstanceInvoked isn't getting triggered. I cloned the code and debugged it locally, and it seems like the message bus was being disposed of before it finished sending the command line arguments to the first instance. Adding a short Thread.Sleep() before calling Cleanup() solved the problem temporarily.

Our application pretty much matches the example code.

This problem occurred on 2.0, though I believe it was also present on 1.0 as we upgraded to try and see if it would fix the problem.

Compiling in NET5 -> BinaryFormatter serialization methods are obsolete and prohibited

File SerializationExtensions.cs uses old methods and you get warnings if compiling in NET5.

Solution:

using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SingleInstanceCore
{
	//For inline serializing and deserializing
	internal static class SerializationExtensions
	{
		internal static byte[] Serialize<T>(this T obj)
		{
			return Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj, GetJsonSerializerOptions()));
		}

		internal static T Deserialize<T>(this byte[] data)
		{
			return JsonSerializer.Deserialize<T>(data, GetJsonSerializerOptions());
		}

		private static JsonSerializerOptions GetJsonSerializerOptions()
		{
			return new JsonSerializerOptions()
			{
				PropertyNamingPolicy = null,
				WriteIndented = true,
				AllowTrailingCommas = true,
				DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
			};
		}
	}
}

Is not this library the same as...?

I used this code some years ago:

var processesCount = Process.GetProcesses().Count(p => p.ProcessName == Process.GetCurrentProcess().ProcessName);
if (processesCount > 1)
{
  Shutdown();
}

Does not it do the same as this library in general?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.