我有一个窗口,显示另一个线程正在运行时的“工作”动画。窗口显示,我可以看到进度条,但动画被冻结。代码在ViewModel上运行,调度程序在构造函数中创建:
_dispatcher = Dispatcher.CurrentDispatcher;
创建动画并运行流程的代码如下:
Working wrk;
protected void Search()
{
ImplementSearch();
wrk = new Working();
wrk.Owner = (MainWindow)App.Current.MainWindow;
wrk.WindowStartupLocation = WindowStartupLocation.CenterOwner;
wrk.HeadingMessage = "Searching...";
wrk.UpdateMessage = "Running your search";
wrk.ShowDialog();
}
void ImplementSearch()
{
System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
System.Windows.Threading.DispatcherOperation
dispatcherOp = _dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
ResetSearch();
string ret = _searchlogic.PerformSearch(SearchTerm, ref _matchingobjects, TypeOfFilter());
if (ret != null)
SearchMessage = ret;
if (_matchingobjects.Count > 0)
{
DataRow row;
foreach (SearchLogicMatchingObjects item in _matchingobjects)
{
row = _dt.NewRow();
row["table"] = item.Table;
row["pk"] = item.PK;
_dt.Rows.Add(row);
}
SelectCurrent();
}
}
));
dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);
}
));
thread.Start();
}
void dispatcherOp_Completed(object sender, EventArgs e)
{
wrk.Close();
}
我无法弄清楚动画停止的原因?有人可以帮忙吗? 感谢
答案 0 :(得分:2)
我认为你想在后台线程上做实际工作,而不是将所有东西编组到UI线程,这就是BeginInvoke所做的!通过使用BeginInvoke在UI线程上执行所有操作,您的动画将无法运行。
Working wrk;
protected void Search()
{
ImplementSearch();
wrk = new Working();
wrk.Owner = (MainWindow)App.Current.MainWindow;
wrk.WindowStartupLocation = WindowStartupLocation.CenterOwner;
wrk.HeadingMessage = "Searching...";
wrk.UpdateMessage = "Running your search";
wrk.ShowDialog();
}
void ImplementSearch()
{
Thread thread = new Thread(new ThreadStart(
delegate()
{
// Call to function which changes UI - marshal to UI thread.
_dispatcher.BeginInvoke((Action)(() => ResetSearch()));
string ret = _searchlogic.PerformSearch(SearchTerm, ref _matchingobjects, TypeOfFilter());
if (ret != null)
{
// Call to function which changes UI - marshal to UI thread.
_dispatcher.BeginInvoke((Action<string>)((r) => SearchMessage = r), ret);
}
if (_matchingobjects.Count > 0)
{
DataRow row;
foreach (SearchLogicMatchingObjects item in _matchingobjects)
{
row = _dt.NewRow();
row["table"] = item.Table;
row["pk"] = item.PK;
_dt.Rows.Add(row);
}
// Call to function which changes UI - marshal to UI thread.
_dispatcher.BeginInvoke((Action)(() => SelectCurrent()));
}
}
wrk.Close();
}));
thread.Start();
}
答案 1 :(得分:0)
您的线程没有任何用处 - 通过使用_dispatcher.BeginInvoke
来运行搜索,您实际上是在UI线程上执行搜索,这会阻止您的动画。仅将后台线程中的调度程序用于操作UI控件或导致触发PropertyChanged事件的操作。