logo
down
shadow

Closing a form that is created in another thread


Closing a form that is created in another thread

Content Index :

Closing a form that is created in another thread
Tag : chash , By : user155548
Date : November 25 2020, 07:27 PM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Closing side thread before closing the main form


Tag : chash , By : sayuki288
Date : March 29 2020, 07:55 AM
Hope that helps First off decide whether or not you really need to be using Invoke at all. It is, and has been for a while now, my opinion that Invoke is one of the most overused techniques for causing an action to occur on the UI thread after it has been initiated from a worker thread. An alternative is to create some type of message object in the worker thread describing the action that needs to be done on the UI thread and place it into a shared queue. The UI thread will then poll this queue on some interval using System.Windows.Forms.Timer and cause each action to occur. This has several advantages.
It breaks the tight coupling between the UI and worker threads that Invoke imposes. It puts the responsibility of updating the UI thread on the UI thread where it should belong anyway. The UI thread gets to dictate when and how often the update should take place. There is no risk of the UI message pump being overrun as would be the case with the marshaling techniques initiated by the worker thread. The worker thread does not have to wait for an acknowledgement that the update was performed before proceeding with its next steps (ie. you get more throughput on both the UI and worker threads). It is a lot easier to handle shutdown operations since you can pretty much eliminate all race conditions that would normally be present when requesting worker threads to gracefully terminate.
public class YourForm : Form
{
  private Thread WorkerThread;
  private volatile bool KillThreads = false;

  private void YourForm_Closing(object sender, FormClosingEventArgs args)
  {
    // Do a fast check to see if the worker thread is still running.
    if (!WorkerThread.Join(0))
    {
      args.Cancel = true; // Cancel the shutdown of the form.
      KillThreads = true; // Signal worker thread that it should gracefully shutdown.
      var timer = new System.Timers.Timer();
      timer.AutoReset = false;
      timer.SynchronizingObject = this;
      timer.Interval = 1000;
      timer.Elapsed = 
        (sender, args) =>
        {
          // Do a fast check to see if the worker thread is still running.
          if (WorkerThread.Join(0)) 
          {
            // Reissue the form closing event.
            Close();
          }
          else
          {
            // Keep restarting the timer until the worker thread ends.
            timer.Start();
          }
        };
      timer.Start();
    }
  }    
}

Properly closing window created on a separate thread using ATL


Tag : cpp , By : Tonci Grgin
Date : March 29 2020, 07:55 AM
With these it helps GetMessage() never returns WM_QUIT. That message forces it to return 0 instead, designed to terminate your message loop.
Beware of the considerable hazards of using PostThreadMessage(). It should never be used on a thread that also displays windows, like the one you are using. The issue is that it doesn't take a HWND argument. So only your message loop can see the message, it won't be delivered to any window with DispatchMessage(). This goes wrong when a modal message loop is entered, the kind that are outside of your control. Like the modal loop that makes MessageBox work. Or the one that Windows uses to allow the user to resize a window. Or the one that DialogBox() uses. Etcetera. Always use PostMessage(), use your own message number.

Closing a wpf window created on a different thread from the background worker WorkRunCompleted


Tag : chash , By : DicksGarage
Date : March 29 2020, 07:55 AM
this one helps. Do the Background in the progress page
If you need to pass (and return) an object then do so in the Progress ctor
private void click(object sender, RoutedEventArgs e)
{
    Progress progressDialog = new Progress();
    progressDialog.Show();
    if (progressDialog != null) progressDialog = null;
}

namespace BackGroundWorkerShowDialog
{
    /// <summary>
    /// Interaction logic for Progress.xaml
    /// </summary>
    public partial class Progress : Window
    {
        BackgroundWorker bwLoadCSV = new BackgroundWorker();
        public Progress()
        {
            InitializeComponent();
            //assign events to backgroundworkers
            bwLoadCSV.WorkerReportsProgress = true;
            bwLoadCSV.WorkerSupportsCancellation = true;
            bwLoadCSV.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            bwLoadCSV.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            bwLoadCSV.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            if (bwLoadCSV.IsBusy != true)
            {
                // Start the asynchronous operation.
                bwLoadCSV.RunWorkerAsync();
            }

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 1; i <= 10; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 10);
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if (e.Cancelled == true)
            {
                //resultLabel.Text = "Canceled!";
            }
            else if (e.Error != null)
            {
                //resultLabel.Text = "Error: " + e.Error.Message;
            }
            else
            {
                //resultLabel.Text = "Done: " + e.Error.Message;
            }
            this.Close();
        }

        private void backgroundWorker1_ProgressChanged(object sender,
            ProgressChangedEventArgs e)
        {
            this.tbProgress.Text = e.ProgressPercentage.ToString();
        }
    }

}

On closing the main Swing window, the other thread on the EventQueue gets not created


Tag : java , By : Search Classroom
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The Java group on facebook.com pointed me to the right direction. The solution is this:
redefine what the close button (X) does on the main GUI.
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);   

Closing Form with X or created button


Tag : chash , By : Bart van Bragt
Date : March 29 2020, 07:55 AM
will help you The FormClosing event handler receives a FormClosingEventArgs argument that contains the property CloseReason, but in your context this is not enough.
Indeed, in both cases (ALT+F4/X-Click or ButtonClick) the argument will contain a CloseReason equal to UserClosing.
private void Button1_Click(object sender, EventArgs e)
{
    this.Tag = "ClosedByUser";
    this.Close();
}
private void LogIn_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.Tag != null)
    {
        // Button clicked
    }
    else
    {
        // other reasons
        // Dp not call Close here, you are already closing 
        // if you don't set e.Cancel = true;
    }
}
Related Posts Related QUESTIONS :
  • WCF Service - Backward compatibility issue
  • Binary patch-generation in C#
  • Tab Escape Character?
  • When do Request.Params and Request.Form differ?
  • The imported project "C:\Microsoft.CSharp.targets" was not found
  • Numeric Data Entry in WPF
  • Print a Winform/visual element
  • C# logic order and compiler behavior
  • When to use an extension method with lambda over LINQtoObjects to filter a collection?
  • How to make a button appear as if it is pressed?
  • C# and Arrow Keys
  • How do you resolve a domain name to an IP address with .NET/C#?
  • Should the folders in a solution match the namespace?
  • How can I evaluate C# code dynamically?
  • CSharpCodeProvider Compilation Performance
  • How can I create Prototype Methods (like JavaScript) in C#.Net?
  • DataTable Loop Performance Comparison
  • CSV string handling
  • What is the best way to do unit testing for ASP.NET 2.0 web pages?
  • High availability
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com