Hattabi Maher Hattabi Maher - 16 days ago 5
C# Question

display hadoop content c#

i would like to get list of files available in my hdfs cluster using .net.
the problem is when i run the code in the main method in Program.cs it worked .and when i try to use the code in a button, the application hungs, it blocks.
Here is the code

using Microsoft.Hadoop.MapReduce;
try {
IHadoop mycluster = Hadoop.Connect();
string[] content = mycluster.StorageSystem.LsFiles("/");
foreach (string s in content) {
Console.WriteLine(s);
}
} catch (Exception exException) {
MessageBox.Show (exException.Message);
}


Many thanks in advance

Answer

If you execute code synchrounously in a WinForms event handler, no UI operations will be performed in that time, because you block the UI thread that handles the Windows message pump. So whenever you have lengthy operations and you want your UI to be reactive, you have to run them in a separate task/thread.

Running operations in a separate task comes with the additional challenge that you have to marshal all UI operations back into the UI thread, because you'll run into an error if you run them in a thread other than the UI thread.

I assume you have a regular Click handler both parameters senderand e (and you are in .NET 4.5 - otherwise you have to use Task.Factory to run the task):

Task.Run(() => {
    try {
        IHadoop mycluster = Hadoop.Connect();
        string[] content = mycluster.StorageSystem.LsFiles("/");
        foreach (string s in content) {
            Console.WriteLine(s);
        }
    } catch (Exception exException) {
        MethodInvoker invoker = delegate() { MessageBox.Show (exException.Message); };
        ((Control)sender).Invoke(invoker);
    }
});
Comments