Monday, June 29, 2009

Programming Tips

1. How to execute critical methods even there is no available memory

Sometimes we need to execute critical tasks even the application faces "out of memroy" exception
like (Database rollback, sending messages from server to clients, saving the working environment..etc)

So how we can execute this method even there is no enough memory.

A good solution for this problem is:

During application startup try to allocate enough dummy memory and when the application faces "out of memory", free this memory and exeute the critical mehods.
2. How to safely access windows control from another thead

The golden windows rule says "Do not access control except through control thread owner".
The control thread owner is the thread which creates the control.
so we have to switch from worker thread to owner thread (it is the main thread in most of the cases) to access the control
see the following code snippt in c#


namespace ThreadingSample
{
public partial class MainForm : Form
{

Thread batchthread = null;

public MainForm()
{
InitializeComponent();
}

void UpdateProgress(int progress)
{

if (prgbarProcess.InvokeRequired)
{
prgbarProcess.Invoke((
MethodInvoker)delegate()
{
prgbarProcess.Increment(progress);
});
}

else
{
prgbarProcess.Increment(progress);
}
}

void StartBatchProcessing()
{

for (int i = 0; i <> {
Thread.Sleep(100);
UpdateProgress(i);
}
}
private void btnProcess_Click(object sender, EventArgs e)
{
batchthread = new Thread(new ThreadStart(StartBatchProcessing)); batchthread.IsBackground = true; batchthread.Start();
}
}
}

No comments:

Post a Comment