简体   繁体   中英

Multi-threading Form and user control

My visual studio project setup is like this: On Form 's panel I add User control(UC) with the code:

in Form :

panel.Controls.Add(UC.Instance);
UC.Instance.Location = new Point(-(panel.Size.Width), 0);
UC.Instance.BringToFront();
roll_in();

in User control :

private static UC _instance;
public static UC Instance
{
    get
    {
        if (_instance == null)
            _instance = new UC();
        return _instance;
    }
}

When I press a button on the Form the User control is added to the Form's panel and I use the following code to slide the User control to its position:

private void roll_in()
{
    while (UC.Instance.Location.X < panel.Location.X)
    {
        UC.Instance.Location = new Point((UC.Instance.Location.X + 2));
        UC.Instance.Refresh();
        if (UC.Instance.Location.X > -10)
            System.Threading.Thread.Sleep(10);
    }
}

When I use the roll_in() all other functions and forms are waiting for this process to finish.

Is there a way I can slide the User control on another thread? I tried calling roll_in() with creating another thread but it says the control was created on another thread.

Can someone help me on guiding me to the right path? How can I do the "animation" without affecting other controls?

Thank you helping

It looks to me like your blocking the UI thread by calling thread.sleep. You generally don't want to do that for any reason. async tasks were created to deal with UI issues like this. Try this code.

private async void roll_in()
{
    while (UC.Instance.Location.X < panel.Location.X)
    {
        UC.Instance.Location = new Point((UC.Instance.Location.X + 2));
        UC.Instance.Refresh();
        if (UC.Instance.Location.X > -10)
            await Task.Delay(10);
    }
}

This should prevent blocking during your sleep cycles.

You can also use Application.DoEvents() inside your loop to process the winforms event queue at regular intervals:

private void roll_in()
{
    while (UC.Instance.Location.X < panel.Location.X)
    {
        UC.Instance.Location = new Point((UC.Instance.Location.X + 2));
        UC.Instance.Refresh();
        Application.DoEvents();
}

}

Info on Application.DoEvents() : https://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM