wpf线程进度控制

2019-07-09 13:57:51 浏览数 (1)

先上源码:

代码语言:javascript复制
namespace touchPy.Loading
{
public class MyLoading
{
public static readonly MyLoading Instance = new MyLoading();
private ScheduleBarWindow _mld;//loading对象
Thread _newWindowThread;//loading线程

object obj = new object();
bool isStart = false;

private MyLoading()
{

}

#region 载入loading控件
/// <summary>
/// 载入loading控件
/// </summary>
public void LoadingStart()
{
isStart = true;
_newWindowThread = new Thread(new ThreadStart(Loading));
_newWindowThread.SetApartmentState(ApartmentState.STA);
_newWindowThread.IsBackground = true;

_newWindowThread.Start();
//threadLst.Add(_newWindowThread);
}
#endregion

#region 线程载入函数
private void Loading()
{
_mld = new ScheduleBarWindow();
_mld.ShowDialog();

//System.Windows.Threading.Dispatcher.Run();

}

#endregion

#region 结束线程,关闭loading
/// <summary>
/// 结束线程,关闭loading
/// </summary>
public void LoadingEnd()
{
if(isStart)

{
while (_mld == null)
{
Thread.Sleep(10);
}

_mld.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
_newWindowThread.Abort();
isStart = false;
}
}
#endregion

#region 结束线程,关闭loading
/// <summary>
/// 结束线程,关闭loading
/// </summary>
public void LoadingEnd(UCTreeView _treeView)
{
Thread _WindowThread = new Thread(LoadingHalt);
_WindowThread.SetApartmentState(ApartmentState.STA);
_WindowThread.IsBackground = true;
_WindowThread.Start(_treeView);
}
#endregion

void LoadingHalt(object data)
{
if (isStart)
{
UCTreeView _tree = data as UCTreeView;
bool bFlag = (bool)_tree.Dispatcher.Invoke(new Func<bool>(()=>{
return _tree.IsLoaded;
}), null);
while (_mld == null || !bFlag)
{
bFlag = (bool)_tree.Dispatcher.Invoke(new Func<bool>(() =>
{
return _tree.IsLoaded;
}), null);
Thread.Sleep(10);
}

_mld.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
_newWindowThread.Abort();
isStart = false;
}
}

}
}

C#线程为单线程模式,所有界面资源线程之间不能共享,对于主线程中后台代码业务处理比较耗时的情况下,需要添加新的线程处理另外一些界面效果。

IsLoad属性,作为界面数据使用数据绑定方式产生延迟的返回结果,告诉用为前台渲染效果是否完成,是否取消ScheduleBarWindow等待加载窗口提示的显示。

Dispatcher.BeginInvokeShutdown关闭消息泵的处理流程,同时关闭了显示窗口。

0 人点赞