你也可以使用System.Threading.Timer來實現函數每30秒運行一次。這樣可以讓主線程保持活動狀態。
void Main()
{
using (MyClass myClass = new MyClass())
{
while(true)
{
// Do some other stuff here (e.g. UI feedback, capture user input).
}
}
}
public class MyClass : IDisposable
{
System.Threading.Timer _timer;
int _functionNumber = 1;
bool _disposed;
public MyClass()
{
_timer = new System.Threading.Timer(MyMethod, null, 0, 30000);
}
~MyClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (_timer != null) _timer.Dispose();
_disposed = true;
}
}
// Timer callback method
private void MyMethod(object state)
{
if (_functionNumber == 1)
{
function1();
_functionNumber = 2;
}
else
{
function2();
_functionNumber = 1;
}
}
//Function1
public int function1()
{
...//some code
}
//function2
public double function2()
{
...//some code
}
}
這是一個功課題嗎?你想要做什麼,爲什麼? – 2012-01-16 15:26:07
@Zonta:「多線程」標籤在這裏做什麼?你想讓它們在不同的線程上執行嗎? – Tigran 2012-01-16 15:29:29
我建議看看System.Threading.Timer,而不是專門花費大部分時間睡眠的線程。 – 2012-01-16 15:30:02