Asynchronous programming.

The code snippet below is a stripped down, example from a real app and illustrates a problem I am experiencing. The idea is to start and stop a process that works in the background (using asynchronous delegate invocation). The process loops until a flag is set to true. In the real app, the process invoves a specific closing-down process and hence the need to wait for the processing to terminate gracefully.  

The problem is the application hangs (for ever) on the WaitOne() call. If I comment this line out, the app appears to work OK. Have I misunderstood how to use the WaitOne() call I need to wait in the main thread for the processing to terminate before I can continue.

BTW I am using Visual Studio 2005 RC1.

public partial class AsyncForm : Form

{

public AsyncForm()

{

InitializeComponent();

}

private delegate void WorkerHandler();

private WorkerHandler Worker;

private IAsyncResult IAResult;

private bool IsDone ;

private void DoWork()

{

while (!IsDone)

{

Thread.Sleep(1500);

}

}

private void AsyncForm_Load(object sender, EventArgs e)

{

btnStart.Enabled = true;

btnStop.Enabled = false;

}

private void btnStart_Click(object sender, EventArgs e)

{

IsDone = false;

Worker = DoWork;

IAResult = Worker.BeginInvoke(null, null);

btnStart.Enabled = false;

btnStop.Enabled = true;

}

private void btnStop_Click(object sender, EventArgs e)

{

btnStop.Enabled = false;

IsDone = true;

IAResult.AsyncWaitHandle.WaitOne();

btnStart.Enabled = true;

}

}




Answer this question

Asynchronous programming.

  • KSH

    Marinos,

    you could use the AsyncCallback delegate to end the asynchronous operation and get any results from that process.

    You will find an example on how to do this here:
    ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_fxadvance/html/d863fa02-b70a-4698-aab7-f7b4adc8070e.htm

    Regards,

    Andres.

  • Asynchronous programming.