如何在不延迟用户界面的情况下检查网络驱动器的可用性 [英] how to check for network drive availability w/o delaying user interface
问题描述
我正在编写一个显示驱动器/目录树的程序,然后填充文件列表(ListView).如果用户尝试选择不可用的网络驱动器,则该程序将停止响应用户输入大约25秒钟.
我认为该程序挂在对DirectoryInfo的调用上.
所以我有这样的东西:
I am writing a program that shows a drive/directory tree which then populates a files list (ListView). If the user tries to select a network drive that isn''t available, the program stops responding to user input for about 25 seconds.
I think the program hangs on a call to DirectoryInfo.
so I have something like this:
private void DirCheck( string startPath) {
var directoryInfo = new DirectoryInfo(startPath);
directoryInfo.GetDirectories();
}
那么我有两种情况可以尝试避免延迟
方案1:
我这样称呼:
then I have two scenarios to try to get around the delay
Scenario 1:
I call it like:
Task Test = Task.Factory.StartNew(() =>
DirCheck("\\netstuff\shared");
在此任务调用中,我尝试省略任何等待任务完成的等待.
方案2:
On this Task call, I tried to omit any wait for the conclusion of the tasks.
Scenario 2:
//BackGroundWorker1
private void TreeWorker(object sender, DoWorkEventArgs e)
{
string strVal;
strVal = (string)e.Argument;
DirCheck(strVal);
}
问题在于该程序仍然挂起25秒.
在完整的代码中,我正在寻找找不到驱动器的异常.
然后,这两个问题是:
1)是否有更好的方法来验证对远程驱动器的访问,从而不延迟用户界面的响应速度?
2)即使从进程的一个线程中调用,GetDirectories方法是否也会始终绑定整个进程?
谢谢.
The problem is that the program still hangs for 25 seconds.
In the complete code, I am looking for an exception to occur if the drive can''t be found.
The two questions then are:
1) Is there a better way to verify access to the remote drive such that there is no delay to the responsiveness of the user interface?
2) Does the GetDirectories method invariably tie-up the whole process, even if called from within a thread of the process?
Thanks.
推荐答案
此方法使用线程从UI线程执行任务,然后以线程安全的方式回调到UI.
This uses threading to perform the task off the UI thread then calls back to the UI in a thread safe way.
using System;
using System.Windows.Forms;
using System.Threading;
namespace ReflectRefCount
{
public partial class Form1 : Form
{
private delegate void dVoidObject(object anyType);
public Form1()
{
InitializeComponent();
}
private void StartLongTaskWithoutUIHang()
{
// here i pass 5000 (5 seconds) to TaskThatTakesALongTime this method is performed on a seperate thread
ThreadPool.QueueUserWorkItem(new WaitCallback(TaskThatTakesALongTime), 5000);
}
private void TaskToUpdateTheUserInterface(object anyType)
{
// need to check this to prevent cross thread errors
if (InvokeRequired)
{
Invoke(new dVoidObject(TaskToUpdateTheUserInterface), anyType);
}
else
{
if (anyType != null)
{
Text = anyType.ToString();
}
}
}
private void TaskThatTakesALongTime(object aNumber)
{
int i = (int)aNumber;
Thread.Sleep(i);
TaskToUpdateTheUserInterface("The task is complete");
}
private void button1_Click(object sender, EventArgs e)
{
StartLongTaskWithoutUIHang();
}
}
}
这篇关于如何在不延迟用户界面的情况下检查网络驱动器的可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!