如果你尝试过这种情况,我想问你们谁。我用c#开发了一个windows应用程序。在主程序(Program.cs)中,我添加了一个线程互斥,只是为了多任务执行在它下执行的许多操作。
//under Program.cs
public static FormOneInstance frmOneInstance;
static void Main()
{
t = new Thread(new ThreadStart(CreateInputOutput));
t.Start();
}
public static void CreateInputOutput()
{
try
{
mutex.WaitOne();
ExecuteManyOperationsHere();
}
finally
{
mutex.ReleaseMutex();
Thread.CurrentThread.Abort(); //Has ThreadAbortException here
t = null;
}
}
public static void ExecuteManyOperationsHere()
{
frmOneInstance =new FormOneInstance (); //this has lot of execution on formLoad that includes ShowSummary()
}
在我的另一个Form FormOneInstance类中,我使用了System.Windows.Forms Timer
private void timer1_Tick(object sender, EventArgs e)
{
ShowSummary();
}
现在,我想在main和UI中分离线程。 谢谢!
答案 0 :(得分:1)
Windows窗体计时器在ui线程上运行,只有一个看到this SO post。
例如,请参阅MSDN上的Threading.Timer
你可以使用一个没有这个东西的计时器。但是当定时器代码想要更改ui中显示的值时,请务必调用ui线程
myTimer= new Timer( handleTimer, null, timerIntervall, Timeout.Infinite );
然后你可以创建一个在ui线程上调用 CreateInputOutput 方法的方法,以显示一个新的ui元素
public void handleTimer(object State)
{
// PLace here the blocking code which shoudl not block the ui
this.invoke(...) // here you can call the method which should be run un the ui thread. Like creating new forms
}
}
有关详细信息,请参阅有关threading timer
的帖子答案 1 :(得分:1)
Since it is not clear what your requirements are, I will assume that what you really want to use is a BackgroundWorker. The following also have samples.
BackgroundWorker.ReportProgress Method (Int32, Object) (System.ComponentModel)
Walkthrough: Multithreading with the BackgroundWorker Component (C# and Visual Basic)