在我的应用中,我有两个按钮:
void Install_1_Click(object sender , RoutedEventArgs e)
{
RunSilentSetup("C:\app1.exe");
}
.
.
.
void Install_2_Click(object sender , RoutedEventArgs e)
{
RunSilentSetup("C:\app2.exe");
}
以及运行安装程序的方法:
void RunSilentSetup(string executableFilePath)
{
//code that runs the setup goes here
}
问题:如果用户单击一个按钮并立即按下第二个按钮,则会引发我无法同时安装的错误。
我的问题:我希望对方法RunSilentSetup
的第二次调用将等到第一次调用完成后才能实现?
编辑安装代码:
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.FileName = executableFilePath;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "/s /v/qn";
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
int exitcode = exeProcess.ExitCode;
if (exitcode == 0)
this.Dispatcher.Invoke(() =>
{
ShowMessage(_vm.ShowSuccess , "Installation was successfully completed");
});
else
this.Dispatcher.Invoke(() =>
{
ShowMessage(_vm.ShowError , $"one or more errors occurred during the installation, exit code: {exitcode}");
});
}
} catch (Exception ex)
{
log.Warn(ex);
}
答案 0 :(得分:2)
答案 1 :(得分:0)
您可以添加一个静态isRunning
类型的字段,如下所示:
void Install_1_Click(object sender , RoutedEventArgs e)
{
RunSilentSetup("C:\app1.exe");
}
void Install_2_Click(object sender , RoutedEventArgs e)
{
RunSilentSetup("C:\app2.exe");
}
static bool setupIsRunning = false;
void RunSilentSetup(string executableFilePath)
{
if(setupIsRunning)
return;
setupIsRunning = true;
//disable both buttons
Install_1.Enabled = false;
Install_2.Enabled = false;
//code that runs the setup goes here
setupIsRunning = false; //set back to false when finished
//re-enable both buttons
Install_1.Enabled = true;
Install_2.Enabled = true;
}
执行此操作的方式不同,但这是我能想到的最简单的方法。
现在,当调用RunSilentSetup
时,它会首先检查setupIsRunning
是否为真。如果是,它将返回(无需进一步执行RunSilentSetup
方法。
如果没有,它将setupIsRunning
设置为true-停止后续呼叫。
完成后,setupIsRunning
设置为false。
答案 2 :(得分:0)
简单,如果它是WPF,则创建一个bool IsWorking
,然后通过绑定转换器将其转换为启用按钮的属性,那么您的问题就得到解决了^^
答案 3 :(得分:0)
也许您可以定义一个Flag属性,并在忙时定义Enable / disable按钮
public bool IsBusyInstalling
{
get
{
return _isBusyInstalling;
}
private set
{
_isBusyInstalling = value;
RaisePropertyChanged("IsBusyInstalling");
}
}
和简单样式:
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsBusyInstalling}" Value="True">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>