【发布时间】:2014-10-09 21:10:44
【问题描述】:
我们开发的 .net Windows 窗体应用程序(vb.net 但 c# 的答案也可以)有一些 API(编辑:是的,我们自己的)允许用户自动执行一些任务。 当应用程序通过 API 启动时,一切都很好,比如 Visual Studio。但是,我们无法着手将我们应用程序的一个已经运行的实例分配给 Visual Studio 中的一个新应用程序对象。 我们已经看到 COM 对象 (getojbect) 可以使用一些方法来访问正在运行的应用程序实例,但是 .net 应用程序呢?
换个说法,我们希望,当用户调用我们应用程序的 New() 构造函数时,新对象指向我们应用程序的运行实例(如果有)而不是尝试创建一个新实例(它顺便说一句,这是不可能的,因为我们通过 Mutex 检查我们的应用程序没有其他实例正在运行,从而使其成为单个实例。
编辑: 用户应用程序中用于自动执行某些任务的示例代码
Imports TheApplication
Public Class WinFormByUser
Private ApplicationObject As TheApplication.MainForm
Public Sub OpenTheApplication()
ApplicationObject = New TheApplication.MainForm
Rem here theapplication should create a new instance if no instance of TheApplication is running. BUT, if an instance of the application
Rem is already running (in a different process, maybe started directly from the user), the ApplicationObject should point to the running
Rem instance from now on, instead of trying to create a new instance
ApplicationObject.DoSomething()
End Sub
End Class
TheApplication 中的示例代码
Imports System.Threading
Public Class MainForm
Private ApplicationOpenedThroughAPI As Boolean = False
Private Shared mtx As Mutex
Private firstInstance As Boolean = False
Dim AppName As String = "TheApplicationName"
Public Sub New()
If Application.ProductName.ToString() <> AppName Then
Rem if TheApplication is opened externally through API the name is different therefore we can determine the boolean value
ApplicationOpenedThroughAPI = True
End If
mtx = New Mutex(True, AppName, firstInstance)
If firstInstance Then
InitializeComponent()
DoAllTheNecessaryStuff()
Else
If ApplicationOpenedThroughAPI = False Then
MsgBox("Application is running, can't open second instance")
Else
ReturnTheRunningInstance()
End If
End If
End Sub
Private Sub ReturnTheRunningInstance()
Rem please help here. what to do?
End Sub
Public Sub DoSomething()
Rem this does something and can be called by API user
End Sub
End Class
请注意,解决方案可能是在应用程序内部的 Sub ReturnTheRunningInstance() 或用户代码中添加一些代码,可能会检查应用程序是否通过 Process.GetProcessesByName("TheApplicationName").Length 和然后做点什么以防万一。
谢谢!
【问题讨论】:
-
不清楚(对我来说)。用户如何调用
New YourApplication(他们指的是您的程序集)?发布一些代码以显示您的意思?还有几次你提到 API,什么 API?你自己?第三者?请张贴该用法以说明清楚。 -
多么奇怪,一个完全不清楚的问题投了三票。认为这值得赞成的人可以解释一下吗?
-
@Steve(将成为 OT 和元答案...):如果用户看到他们无法回答的问题,那么有 3(我认为)可能的反应:1. 忽略,2. 否决/标志关闭 3. 投票:D
-
@Steve 没问题。我发现这个问题很有趣,因为我可以很好地想象作者想要做什么。这个想法是获取在单独进程上运行的类的实例。这就是
.NET Remoting在 .NET 1.1 附近的某个地方,它的所有MarshalByRefObject和透明代理类。所以这个问题对我来说很有趣,因为事情是如何随着时间变化的。至少现在远程处理不再受到赞扬,并且广泛建议使用自托管服务。也许我会在这里看到一些不同的东西,所以我赞成鼓励人们回答。 -
基于问题中的有限信息,我建议开发人员可以随意实例化任意多次的包装器。然后,该包装器将负责定位应用程序的单个运行实例或创建一个新实例。一旦应用程序被定位/启动,包装器将通过跨进程机制转发调用(与刚才提到的@AlexanderManekovskiy 相同)。这可能适用于 WCF,尽管模式有点不寻常。
标签: c# .net vb.net visual-studio