我有一个C# winform应用程序,它需要以同步方式运行多个示例。目标是:
如果exe运行3次,则它运行exe的第一个示例,其余的将等待,直到第一个示例完成处理。然后,下一个等待的执行程序将运行和处理等等。
exe将一个接一个地运行,直到它完成处理,然后exe将自动终止af。
知道怎么做吗
我已经在下面试过了:
private void CheckInstance()
{
bool _returnValue = true;
string _lockFile = string.Empty;
Random _rnd = new Random();
int _randomValue = _rnd.Next(100, 200);
int _rndmiliSec = 0;
_rndmiliSec = DateTime.Now.Millisecond * _rnd.Next(2, 6);
_lockFile = string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName));
while (_returnValue)
{
_returnValue = File.Exists(_lockFile);
if (_returnValue)
{
Thread.Sleep(1000);
this.Hide();
}
else
{
try
{
Thread.Sleep((_rnd.Next(1000) + _rndmiliSec) + _rnd.Next(1000, 1500));
Functions.WriteLog(_lockFile, "Starting the process...");
Functions.WriteLog(_lockFile, string.Format("Start Time : {0}", paramPrintTime));
File.SetAttributes(_lockFile, FileAttributes.ReadOnly);
this.Show();
break;
}
catch (Exception)
{
_returnValue = false;
}
}
}
}
private void DeleteInstance()
{
try
{
File.SetAttributes(string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName)), FileAttributes.Normal);
File.Delete(string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName)));
}
catch (Exception)
{
}
}
private void Form_Shown(Object sender, EventArgs e)
{
_backWorker.RunWorkerAsync();
}
private void FormClosed(object sender, FormClosedEventArgs e)
{
DeleteInstance();
}
private void Form_Load(object sender, System.EventArgs e)
{
CheckInstance();
}
BackgroundWorker _backWorker = new BackgroundWorker();
public Form()
{
InitializeComponent();
_backWorker.WorkerReportsProgress = true;
_backWorker.ProgressChanged += _backWorker_ProgressChanged;
_backWorker.RunWorkerCompleted += _backWorker_RunWorkerCompleted;
_backWorker.DoWork += _backWorker_DoWork;
}
private void _backWorker_DoWork(object sender, DoWorkEventArgs e)
{
Do some work processing...
}
private void _backWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
private void _backWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pg.Value = e.ProgressPercentage;
lblIndicator.Text = e.UserState.ToString();
}
当exe运行3个示例时,第一个示例将运行,而第二个和第三个隐藏一段时间,等待第一个示例完成。但是,在第一个示例完成该过程后,第二个和第三个示例同时运行。
有什么想法吗?谢谢。
1条答案
按热度按时间zynd9foi1#
也许这可以工作:
在Main函数中调用此函数(在打开mainForm之前),如果它为false Application.Exit()else显示您的表单。