用户界面因大量计算而冻结 [英] UI freezes on heavy calculation
本文介绍了用户界面因大量计算而冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将大量文件加载到内存中,但是根据这种计算,我的应用程序冻结了。
I am loading huge files to the memory but on this calculation my application is freezes .
任何人都知道我的代码有什么问题吗?
Any idea what is the issue with my code ?
public void Drop(DragEventArgs args)
{
BackgroundWorker worker = new BackgroundWorker();
string fileName = IsSingleTextFile(args);
if (fileName == null) return;
worker.DoWork += (o, ea) =>
{
try
{
StreamReader fileToLoad = new StreamReader(fileName);
string filecontent = fileToLoad.ReadToEnd();
fileToLoad.Close();
// providing the information to the UI thread
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() => SfmLogFile = filecontent));
}
catch (Exception)
{
throw;
}
};
worker.RunWorkerCompleted += (o, ea) =>
{
args.Handled = true;
IsBusy = false;
};
// Mark the event as handled, so TextBox's native Drop handler is not called.
IsBusy = true;
worker.RunWorkerAsync();
}
推荐答案
I' d将您的样本转换为如下形式:
I'd transform your sample to something like this:
public void Drop(DragEventArgs args)
{
string fileName = IsSingleTextFile(args);
if (fileName == null) return;
// It is better to create worker after check for file name.
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (o, ea) =>
{
try
{
string filecontent = ReadAllText(fileName);
ea.Result = fileContent;
}
catch (Exception)
{
throw;
}
};
worker.RunWorkerCompleted += (o, ea) =>
{
var fileContent = ea.Result as string;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() => SfmLogFile = filecontent));
// if IsBusy propery is not on the UI thread, then you may leave it here
// otherwise it should be set using the dispatcher too.
IsBusy = false;
};
IsBusy = true;
worker.RunWorkerAsync();
// Mark the event as handled, so TextBox's native Drop handler is not called.
args.Handled = true;
}
这篇关于用户界面因大量计算而冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文