简体   繁体   中英

Running Class Methods in BackgroundWorker

I have a Class which has about a dozen Methods in it. Most of the Methods execute and complete rather quickly. However two off the Methods can, on occasion, take quite some time to run their course. So from looking around, I think I want to run them in a BackgroundWorker. But I am just not getting my head around the details of this yet. I am a bit of a noob.

My main form for the application;

namespace EncodeDecode
{
    public partial class EnDecoder : Form
    {

        CodeMachine coder = new CodeMachine();
        // char[] letters = new char[94 + 33];
        List<string> words = new List<string>();

    }
}

public class CodeMachine
{
    public bool Encode()  // This takes a while
    {
    }

    public bool Decode()  // This takes a while
    {
    }

    public bool Load()  // This is quick
    {
    }

     .....              // The rest are quick too
     .....
}

}

So, how do I run the two lengthy Methods inside the coder instance of my class, in the BackgroundWorker?

Maybe you can make your methods async and await for their results, so something like:

CodeMachine coder = new CodeMachine();

// run this async and await response (will not block the UI)
// it will sort of use it as a checkpoint to continue from
await coder.EncodeAsync();

Then in your CodeMachine you make an async method that returns the result:

public class CodeMachine
{
    // naming convention has it ending with Async
    public async Task<bool> EncodeAsync()
    {
        // do something that takes a while here ....
    }
}

Here is more info.

The BackgroundWorker is a class that can be used to execute a single method on a separate thread. Its an easy way to use threading for beginners in my opinion.

From what your asking it looks like your looking to asynchronously run the methods that take a long time.

I usually do this with delegates and BeginInvoke because thats what I'm used to and my shop just recently moved to .Net 4.0.

Dimitar's answer with use of tasks would probably be the simpler way to go. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM