TopMost property not working with async

Kumar, Thrainder (MIND) 176 Reputation points


public void main_click(object sender, EventArgs e)
//DO something
//DO something

//Here the popup opens at the most front but gets backside when I click on another window of my application.
//I want to make poptest1 at the front so that the user can't click on other windows like happens in without async method.

public async void mainAsync_click(object sender, EventArgs e)
//DO something
await Task.Run(() => { test2(); });
//DO something

public void test2()
poptest1.TopMost = true;
poptest1.TopLevel = true;

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,468 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,186 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,496 Reputation points

    Hi KumarThrainderMIND-0302,
    When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.
    So if you want to make form(poptest1) at the front so that the user can't click on other windows, there is no need to use Task.Run() in your code.
    And async methods won't block the current thread, so you can use them from the UI thread directly.
    Please refer to the following code:

    Form2 f2 = new Form2();  
    private async void Button1_Click(object sender, EventArgs e)  
        await this.test2();       
    public async Task test2()  
        f2.TopMost = true;  
        f2.TopLevel = true;  
        await Task.Delay(1000);  

    Best Regards,
    Daniel Zhang

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments