在没有ThreadPool的wpf (c#)应用程序中,对相同的任务一次又一次地重用同一个线程
本文关键字:一次又一次 任务 线程 同一个 wpf ThreadPool 应用程序 | 更新日期: 2023-09-27 17:53:51
创建一个MVVM应用程序,其中应用程序希望通过单击按钮连接到服务器。单击该按钮后,将创建一个线程连接到服务器,以便UI不会冻结和终止(超时时间为15秒)。下次点击按钮将再次创建连接到服务器的新线程并终止。
但是第一次我想创建一个新线程,后来我想重用这个线程(不是新的)来做"连接"任务,如果应用程序没有关闭,用户点击了相同的按钮。
这可能吗?
代码如下:
Class ConnectViewModel:BaseViewModel
{
public void ConnectToServer()
{
ConnectButtonEnable = false;
ConnectingServerText = Properties.Resources.TryingToConnectServer;
Thread thread = new Thread(new ThreadStart(connect));
thread.Start();
thread.Join();
}
public void connect()
{
bool bReturn = false;
UInt32 iCommunicationServer;
bReturn = NativeMethods.CommunicateServer(out iCommunicationServer);
if (!bReturn || NativeMethods.ERROR_SUCCESS != iCommunicationServer)
{
ConnectingServerText = Properties.Resources.UnableToConnectToServer;
}
else if (NativeMethods.ERROR_SUCCESS == iCommunicationServer)
{
ConnectingServerText = properties.Resources.SuccessfullyConnectedServer;
}
ConnectButtonEnable = true;
return;
}
}
由于问题的措辞,我建议你阅读MVVM和异步模式,一些例子:
- http://msdn.microsoft.com/en-us/magazine/dn605875.aspx
- http://richnewman.wordpress.com/2012/12/03/tutorial-asynchronous-programming-async-and-await-for-beginners/
但一般来说,在gui应用程序中编码时,使用async
,不要手动创建新线程。如果任务在"运行"时不应该被调用,通过Interlocked.CompareExchange
进行测试和设置,并存储一些状态。
使用线程进行并行工作,而不是"在网络上等待"。
您可以使用TPL来实现这一点。
private Task previous = Task.FromResult(true);
public Task Foo()
{
previous = previous.ContinueWith(t =>
{
DoStuff();
});
return previous;
}
通过将每个操作调度为前一个操作的延续,您可以确保每个操作直到前一个操作完成时才开始,同时仍然在后台线程中运行所有操作。
不用担心创建和管理线程,只需使用ThreadPool.QueueUserWorkItem
代替-它非常高效。