I'm working on an Export-Tool from a Database which I had written in Visual Basic.net before a long time.
I switched to C# and like to reprogram it in C# since I've gathered quite a little bit more experience than I had before :-)
My C# application's UI is hanging because there is a big database query to do. So I've informed myself about asynchronous programming. Tried threads and tasks as well but I'm having problems to find the right method for my concerns.
This is what I have: it's a Windows Forms application and there's a start button which creates a new thread.
The Method called Export is a non static method which I've created in a second class file named actions.cs
. It's non static because the method should be reused often in the code but with different parameters.
So I instantiated the method in the Button_Clicked
Event on Form1 with the corresponding parameters:
actions KuliMon = new actions()
{
ExportPath = settings.ReadActSetting("baexport", "ExportPfad", ""),
Trennzeichen = settings.ReadGlobSetting("Trennzeichen", ";"),
ConnectionString = settings.ReadGlobSetting("Mand1_odbc", ""),
SQLFile = "kuli.sql",
ExportAktion = "kuli"
};
Then I've started the thread from the Button_click event like this:
Thread ExportThread = new Thread(KuliMon.Export);
ExportThread.Start();
This works. No sticking GUI. But now there is the problem. My method Export in actions.cs is exporting the DB-Query into a csv-File but should also return the result in a string variable which then I can display in a TextBox on Form1.
By reading a little bit around I've found the Invoke-Method this helped quite a little bit. Under Thread.Start() I've added the following:
this.Invoke((MethodInvoker)delegate
{
tx_main_t1.Text = "Hello";
});
When I've clicked the button the TextBox says "hello". But instead of hello I need the Return string from my method Export running in the thread. And here's the problem how can I get the string with the queried results.
In my understanding the thread method has to call a void-method and must not return a value.
I had an idea of creating a public property string and fill the string in Export with the return value like this:
public string results { get; set; }
Instead of using return ReturnValue
in Method Export I've tried
results = ReturnValue;
In Form1 I then tried to fill the TextBox with KuliMon.results but it's empty because I've made an instance of Export as I think.