Main question

If i have a class

public Class foo
{
    public foo()
    {
        myclass = new myclass(param)
        myclass.initiateState();
        val = myclass.getValues();
    }
}

Class.initiateState() is a lengthy process that runs in my GUI constructor that I wanted to run with a thread, however the next line goes to the same class to return some data, but if I run the first line in a new thread, which then runs before it will be able to finish.

How can I solve this problem?

+3
source share
4 answers

Do it BackgroundWorker.

Inside the event method, DoWorkadd a call myClass.initiateState(). Inside the event method, RunWorkerCompletedcallmyClass.getValues();

This will cause it to initiateStatebe launched in the background thread, and at the end it will light up getValuesin the GUI thread.

, , # , Java. initiateState getValues:)

+11

:

public Class foo
{
    public foo()
    {
        myclass = new myclass(param)
        new Action( () => myclass.initiateState() ).BeginInvoke(initiateStateFinished, null)
    }

   private void initiateStateFinished(IAsyncResult ar)
   {
      val = myclass.getValues();
      //other actions
   }
}

    public foo()
    {
        myclass = new myclass(param)
        new Action( () => myclass.initiateState() )
           .BeginInvoke(_ => val = myclass.getValues(), null)
    }
+4

, BOTH

    myclass.initiateState();
    val = myclass.getValues();

( val)?

, .NET 4.0 Tasks, :

        var someBackgroundTask = new System.Threading.Tasks.Task<*return type of GetValue()*>(() =>
            {
                myclass.initiateState();
                return myclass.getValue();
            });
        someBackgroundTask.Start();

someBackgroundTask.Result, . , - ( ), Task. someBackgroundTask.IsCompleted, , , someBackgroundTask.Wait(), .

: , , , .;)

+1

, foo . , , , foo - , .


First create a DoWork method in foo:

private void DoWork() {
    myclass = new myclass(param);
    myclass.initiateState();
    val = myclass.getValues();
}

Then modify the constructor to run it as a stream:

public foo() {
   Thread workerThread = new Thread(this.DoWork);
   /* ... do other stuff ... */      
}

Take a look at this: http://msdn.microsoft.com/en-us/library/7a2f3ay4.aspx

0
source

Source: https://habr.com/ru/post/1795734/


All Articles