I am working on a windows application which freezes most of the time on button click events on Home Page. Please find the code below for your reference. Thanks
using System; using System.Windows.Forms; namespace FileMigrationAgen { public partial class HomePage : Form { public HomePage() { InitializeComponent(); } private void tableLayoutPanel4_Paint(object sender, PaintEventArgs e) { } private async void button1_Click(object sender, EventArgs e) { SharepointMigration sharepointMigration = new SharepointMigration(); sharepointMigration.Show(); this.Hide(); } private async void button2_Click(object sender, EventArgs e) { OneDriveMigration oneDriveMigration = new OneDriveMigration(); oneDriveMigration.Show(); this.Hide(); } private void HomePage_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } } }
async
await
private async void button1_Click(object sender, EventArgs e) { //Make the constructor simple and not time consuming, //only initialize variables with basic values //You can do the "work" in a seperate method that //will be called after the form is constructed. //To work correctly, the main UI thread needs //to create/construct the form. SharepointMigration sharepointMigration = new SharepointMigration(); //using async here because your button signature in //your post used async. If the method does not need //to be async then remove async and the await operator. //The ContinueWith allows the form to show when the //worker task - sharepointMigration.InitializeForm() //completes await Task.Run(async() => await sharepointMigration.InitializeForm()).ContinueWith((x) => { //Note the use of the extension method which //ensures the code executes on the Main UI Thread sharepointMigration.UIThreadInvoke(() => { sharepointMigration.Show(); this.Hide(); }); }); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)