C multithreading and methods for accessing interface controls across threads

  • 2020-12-20 03:43:56
  • OfStack

This article illustrates the C# multithreading and cross-threading approach to interface controls. Share to everybody for everybody reference. The specific analysis is as follows:

When writing WinForm to access WebService, we often encounter the phenomenon of interface stuck because of network delay. Enabling a new thread to access WebService is one possible approach.

Typically, there are the following examples of starting a new thread:

private void LoadRemoteAppVersion()  

    if (FileName.Text.Trim() == "") return; 
    StatusLabel.Text = " Being loaded "; 
    S_Controllers_Bins.S_Controllers_BinsSoapClient service = new S_Controllers_Bins.S_Controllers_BinsSoapClient(); 
    S_Controllers_Bins.Controllers_Bins m = service.QueryFileName(FileName.Text.Trim()); 
    if (m != null) 
    { 
        //todo: 
        StatusLabel.Text = " Load the success "; 
    }else 
        StatusLabel.Text = " Load failed "; 

private void BtnLoadBinInformation(object sender, EventArgs e) 

    Thread nonParameterThread = new Thread(new ThreadStart(LoadRemoteAppVersion)); 
    nonParameterThread.Start();   
}

When running a program, if you want to operate an interface control within a thread, you may be prompted that you cannot access the interface control across threads. There are two ways to do this:

1. Change the startup procedure 1 below:

/// <summary>  
/// The main entry point to the application.  
/// </summary> 
[STAThread] 
static void Main() 

    Application.EnableVisualStyles();  
    System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; 
    Application.SetCompatibleTextRenderingDefault(false); 
    Application.Run(new Form1()); 
}

2. Use a delegate
public delegate void LoadRemoteAppVersionDelegate(); // Define delegate variables 
private void BtnLoadBinInformation(object sender, EventArgs e) 

    LoadRemoteAppVersionDelegate func = new LoadRemoteAppVersionDelegate(LoadRemoteAppVersion);//<span style="font-family: Arial, Helvetica, sans-serif;">LoadRemoteAppVersion Don't need to modify </span> 
    func.BeginInvoke(null, null); 
}

Hopefully this article has helped you with your C# programming.


Related articles: