Running a windows form in a separate thread

前端 未结 4 1385
孤独总比滥情好
孤独总比滥情好 2021-01-15 02:10

I am dealing with running a control in a form, however the form itself is of no value to me. I essentially want the form to run a task and return a value, however for that I

相关标签:
4条回答
  • 2021-01-15 02:41

    I think the simplest solution is to just raise an event from the form once the task has completed.

    void RunTask()
    {
        Form form = new Form();
        form.TaskCompleted += new EventHandler(form_TaskCompleted);
        form.Show();
    }
    
    void form_TaskCompleted(object sender, EventArgs e)
    {
        object result = ((Form)sender).GetResult();
    }
    

    Edit: Of course you'd want to dispose the form and unhook that event once it's completed etc..

    0 讨论(0)
  • 2021-01-15 02:41

    Why are you running tasks in a form?

    This sounds like you have your UI and program logic tightly integrated. This is bad design.

    In general, You can get data from a worker thread the standard way. Worker stores data in a thread safe data structure, then sends an event to the main thread signaling the data is available.

    0 讨论(0)
  • 2021-01-15 02:54

    I did this once for my project

    var frmNewForm = new Form1();
    var newThread = new System.Threading.Thread(frmNewFormThread);
    
    newThread.SetApartmentState(System.Threading.ApartmentState.STA);
    newThread.Start();
    

    And add the following Method. Your newThread.Start will call this method.

    public void frmNewFormThread()
    {
        Application.Run(frmNewForm);
    }
    
    0 讨论(0)
  • 2021-01-15 03:00

    I've got two ideas in my mind:

    1. Run delegate method

      IAsyncResult ar = del.BeginInvoke(callback, state);

      ... do the task

      EndInvoke(ar); // waiting for task result if you allow to wait

    2. Separate thread

    The best way may be use separate thread to do the task and call delegate in this thread to inform main thread about work finish.

    edit: or Worker like suggest my predecessor

    0 讨论(0)
提交回复
热议问题