Show form on top of parent during background work

Not sure if doing myForm.ShowDialog() during a background worker is the issue, but in my application, I have a background worker check for data, and if the data is empty, I do myForm.ShowDialog(). The only problem is, it will show up underneath the parent form, but still be centered relatively to parent when I have CenterParent set as the start position. From my understanding ShowDialog() should make the form show on top by default, but wondering why its going underneath.

Is it because I am doing it during a background worker? I tried doing myForm.ShowDialog(this) but I keep getting this error.

System.InvalidOperationException: ‘Cross-thread operation not valid: Control ‘MainForm’ accessed from a thread other than the thread it was created on.’

How can I reference this during a background worker, or is there any other reason/solution to have myForm.ShowDialog() stay on top?

2

Your question is about showing a notification form on top of parent during background work (emphasis mine on during). That is, if you only want to do background work and pop up a modal or non-modal notification when it’s done, just await the Task and show the notification when you get execution back. I’d like to attempt to answer the question as worded, and there’s a subtle distinction to be made here. It seems to me there are at least two variations: a notification that allows the background work to keep running (Snooze/Dismiss Clock Runner example), and one that blocks the background work, but not the UI (Continue/Cancel Work in Stages Example). So, one might consider implementing the notification Form in a manner that can optionally await when shown as a non-modal, and also stays on top of the parent form as per the spec. By checking the DialogResult after awaiting ShowAsync() the background task can either continue or cancel in response.

The general advice being offered about marshaling onto the UI thread with Invoke or preferably BeginInvoke before interacting with the UI controls from the background thread still stands.

Custom notification form

public partial class Notification : Form
{
    public Notification()
    {
        InitializeComponent();
        ControlBox = false;
        StartPosition = FormStartPosition.CenterParent;
        buttonCancel.Click += (sender, e) =>
        {
            DialogResult = DialogResult.Cancel;
            localSafeSignalSemaphore();
        };
        buttonOK.Click += (sender, e) =>
        {
            localSafeSignalSemaphore();
        };
        void localSafeSignalSemaphore()
        {
            Owner?.BeginInvoke(() =>
            {
                Hide();
                Owner?.BringToFront();
                // Ensure that there's always "something to release".
                // We constrained maxCount on the semaphore to hold
                // ourselves accountable for managing this correctly.
                _busy.Wait(0);   // If count is 1, decrement it...
                _busy.Release(); // ... even if we're just going to increment it again.
            });
        }
    }

    SemaphoreSlim _busy = new SemaphoreSlim(1, maxCount: 1);

    /// <summary>
    /// Alternative to `Show` that is awaitable.
    /// </summary>
    public async Task ShowAsync(
            Control owner, 
            string message,
            string? ok = null,
            string? cancel = null
        )
    {
        // Block the awaiter unconditionally, but allow reentry.
        _busy.Wait(0);
        DialogResult = DialogResult.None;
        if(owner is null) throw new ArgumentNullException(nameof(owner));
        owner.BeginInvoke(() =>
        {
            Configure(message, ok, cancel);
            if (!Visible)
            {
                base.Show(owner);
                CenterToParent();
            }
        });
        await _busy.WaitAsync();
    }
    public DialogResult ShowDialog(
            Control owner,
            string message,
            string? ok = null,
            string? cancel = null)
    {
        Configure(message, ok, cancel);
        return base.ShowDialog();
    }
    private void Configure(
            string message,
            string? ok = null,
            string? cancel = null)
    {

        buttonOK.Visible = !string.IsNullOrWhiteSpace(ok);
        buttonOK.Text = ok ?? "OK";
        buttonCancel.Text = cancel ?? "Cancel";
        textBoxMessage.Text = message ?? string.Empty;
    }
    [Obsolete("Use ShowAsync with this class")]
    public new void Show() => throw new NotImplementedException();
    
    [Obsolete("Use ShowAsync with this class")]
    public new void Show(IWin32Window owner) => throw new NotImplementedException();

    
    [Obsolete("Use ShowDialog(owner, message, ok, cancel), with this class")]
    public new void ShowDialog() => throw new NotImplementedException();

    [Obsolete("Use ShowDialog(owner, message, ok, cancel), with this class")]
    public new void ShowDialog(IWin32Window owner) => throw new NotImplementedException();
}

Notify on, but do not suspend, background (Clock Runner Example)

Here the goal is to remind user every so often that time has elapsed, keep the clock running in the meantime, keep the main UI responsive, and if the user hasn’t dismissed the notification when the next notification happens, update the visible notification rather than showing a new one.

public MainForm()
{
    InitializeComponent();
    buttonStartWorkload.Click += async (sender, e) =>
        await RunClockWithReminders();
}
private async Task RunClockWithReminders()
{
    try
    {
        UpdateMainForm(enableButton: false, label: $@"{DateTime.Now:hh:mm:ss}");
        using (var notification = new Notification())
        {
            await Task.Run(async () =>
            {
                var stopwatch = Stopwatch.StartNew();
                while (notification.DialogResult == DialogResult.None)
                {
                    for (int i = 0; i < 10; i++)
                    {
                        if (notification.DialogResult == DialogResult.Cancel) return;
                        await Task.Delay(TimeSpan.FromSeconds(1));
                        if (notification.DialogResult == DialogResult.Cancel) return;
                        UpdateMainForm(enableButton: false, label: $@"{DateTime.Now:hh:mm:ss}");
                    }
                    // Discard/Ignore the return task in this case
                    _ = notification.ShowAsync(
                        this,
                        $"Performed {(int)stopwatch.Elapsed.TotalSeconds} seconds total work.",
                        ok: "Snooze",
                        cancel: "Dismiss");
                }
            });
        }
    }
    finally
    {
        UpdateMainForm(enableButton: true);
    }
}
private void UpdateMainForm(bool enableButton, string? label = null, string? title = "")
{
    BeginInvoke(() =>
    {
        buttonStartWorkload.Enabled = enableButton;
        if (label is string) this.label.Text = label;
        if (title is string)
        {
            // Specifically, on empty, copy label to Title
            if (title == string.Empty) Text = this.label.Text;
            else Text = title;
        }
    });
}

Notify on stage, blocking background work pending Continue/Cancel (Work in Stages Example)

Here the goal is to inform user that a portion of the work has completed before continuing to do more background work. The total elapsed time of the background task can be >> the total of the task stages in this case. There may be a temptation to ShowDialog() to keep the background from doing any more work until user confirms it, but don’t do that.

public MainForm()
{
    InitializeComponent();
    buttonStartWorkload.Click += async (sender, e) =>
        await RunBackgroundWorkInStages();
}
private async Task RunBackgroundWorkInStages()
{
    try
    {
        UpdateMainForm(enableButton: true, label: $@"{Stage.Idle}");
        using (var notification = new Notification())
        {
            var stopwatchTotal = Stopwatch.StartNew();
            foreach (Stage stage in Enum.GetValues<Stage>().Skip(1))
            {
                var stopwatchTask = Stopwatch.StartNew();
                UpdateMainForm(enableButton: false, label: $@"{stage}", title: $"{DateTime.Now:hh\:mm\:ss} {stage}");
                await Task.Delay(TimeSpan.FromSeconds(10));
                UpdateMainForm(enableButton: false, label: $@"{stage}", title: $"{DateTime.Now:hh\:mm\:ss} {stage}");
                stopwatchTask.Stop();
                await notification.ShowAsync(
                    this,
                    $"Performed {stage} in {stopwatchTask.Elapsed.TotalSeconds} seconds.{Environment.NewLine}" +
                    $"Total time is {stopwatchTotal.Elapsed.TotalSeconds} seconds",
                    ok: "Continue",
                    cancel: "Cancel");
                if (notification.DialogResult == DialogResult.Cancel) break;
            }
        }
    }
    finally
    {
        UpdateMainForm(enableButton: true, label: $@"{Stage.Idle}");
    }
}

ShowDialog Notification after work is complete (‘not’ the question as worded)
public MainForm()
{
    InitializeComponent();
    buttonStartWorkload.Click += async (sender, e) =>
        // Simulate workload with delay
        await NotifyWhenComplete(
            work: () => 
            Task
            .Delay(TimeSpan.FromSeconds(10))
            .Wait(),
            true
            );
}
private async Task NotifyWhenComplete(Action work, bool notify)
{
    try
    {
        UpdateMainForm(enableButton: false, label: $@"{DateTime.Now:hh:mm:ss}");
        await Task.Run(work);
        if (notify) using (var notifier = new Notification())
        {
            notifier.ShowDialog(this, "Backgound work is complete.", cancel: "Close");
        }
    }
    finally
    {
        UpdateMainForm(enableButton: true, label: $@"{DateTime.Now:hh:mm:ss}");
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật