开发者

Try codesnippet until condition is True

开发者 https://www.devze.com 2022-12-10 10:12 出处:网络
this is probably a nobraner, but I can\'t figure it out. I\'ve got this function which converts wav files to mp3. I call this from my button_click handle. The thing is, when the conversion is started

this is probably a nobraner, but I can't figure it out. I've got this function which converts wav files to mp3. I call this from my button_click handle. The thing is, when the conversion is started, the rest of the code in the button_click handler continue, while the conversion is happening in a different thread.

Now, I need the rest of the code in the button_click handle so continue to try until a boolean is true, so开发者_如何转开发 that I know that the conversion is done before the rest of the code continues.

I've tried using Do While but it didn't seem to do the trick. Perhaps it's just me though..


Is this a client application? Sounds like a great application for BackgroundWorker.

To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished.

BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler
                                   (bw_RunWorkerCompleted);
....

private void button1_Click(object sender, EventArgs e)
{
    bw.RunWorkerAsync(filename);
}

static void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = (BackgroundWorker)sender;
    string filename = (string)e.Argument;
    e.Result = DoConversion(filename);
}

static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    label.Text = "Done: " + e.Result.ToString();
    DoSomethingWhenConversionComplete();
}


This is called a spin-wait and is not the best way to accomplish your task:

// IsConversionComplete will be set by some other thread
while(!IsConversionComplete){
  Thread.Sleep(100);
}
// carry on

A much more efficient solution requires a synchronization structure like a mutex or use of events.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号