Code if (System.Diagnostics.Process.GetProcessesByName(
Process.GetCurrentProcess().ProcessName
).Length >1) {
MessageBox.Show("对不起,不能同时启动多个应用程序。"); return;
}
多线程和异部调用:
1.EndInvoke用法
Code class Program
{ privatestaticint newTask(int ms)
{
Console.WriteLine("任务开始");
Thread.Sleep(ms);
Random random =new Random(); int n = random.Next(10000);
Console.WriteLine("任务完成"); return n;
} privatedelegateint NewTaskDelegate(int ms);
Code class Program
{ privatestaticint newTask(int ms)
{
Console.WriteLine("任务开始");
Thread.Sleep(ms);
Random random =new Random(); int n = random.Next(10000);
Console.WriteLine("任务完成"); return n;
} privatedelegateint NewTaskDelegate(int ms);
staticvoid Main(string[] args)
{
NewTaskDelegate task = newTask;
IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); while (!asyncResult.IsCompleted)
{
Console.Write("*");
Thread.Sleep(100);
} //由于异步调用已经完成,因此,EndInvoke会立刻返回结果 int result = task.EndInvoke(asyncResult);
Console.WriteLine(result);
Console.ReadLine();
}
}
3.使用回调方式返回结果
Code class Program
{ privatestaticint newTask(int ms)
{
Console.WriteLine("任务开始");
Thread.Sleep(ms);
Random random =new Random(); int n = random.Next(10000);
Console.WriteLine("任务完成"); return n;
} privatedelegateint NewTaskDelegate(int ms);
staticvoid Main(string[] args)
{
NewTaskDelegate task = newTask;
task.BeginInvoke(2000, delegate(IAsyncResult asyncResult) { if (asyncResult ==null) return;
Console.WriteLine((asyncResult.AsyncState as NewTaskDelegate).EndInvoke(asyncResult));
},task);
Console.WriteLine("Main do something over!");
Console.ReadLine();
}
}