I'm making a winform application, with c# .net. This application runs an algorithm开发者_JAVA技巧 in a background thread, to make calculations. But i have 2 diffrent algortihm to count the same, and i would like to switch between them, in runtime. These algorithms run in every 5 sec, so they are infinte. What i tried, that implement with strategy pattern, and the thread, runs the abstract method. And when i click on a menuitem, i change the concrete Strategy object, so the method will be the same, but the implementation will be different. But it doesnt worked for me, the old algorithm ran continously, which i started at the beginning. So in summary. Is there a way to change the running thread method in runtime?
Thank you for your help.
Sample Code:
//the thread starts the context object's method, which calls, the abstract strategy algorithm method
appList = new RunAppList();
myThread = new Thread(new ThreadStart(appList.Measure));
myThread.IsBackground = true;
//In these methods i would like to switch, i set the concretestrategy objects, these object returns with the results through the resultcallback delegate
public void OnPowerSet(object sender, EventArgs e)
{
try
{
appList.SetMeasureAlgorithm(new WindowMeasureWithPowerSet(new ListCallback(ResultCallBack)));
if (!myThread.IsAlive)
myThread.Start();
}
catch (ThreadStartException te)
{
Console.WriteLine(te.ToString());
}
}
public void OnPolygon(object sender, EventArgs e)
{
appList.SetMeasureAlgorithm(new WindowMeasureWithPoligon(new ListCallback(ResultCallBack)));
if (!myThread.IsAlive)
{
myThread.Start();
}
}
enter code here
Update: Thank everyone for help, im a bit dumm for programming so i tried instead your advise,in my way. I'm not sure if this is the correct solution for my problem, but it seems that works. I moved thread form the concretestrategy object, to the context object.
This could be due to one of many things. The two things that seem most likely:
- Make sure your background thread is checking the variable where you set the method to use within it's loop, so it sees that it should change methods.
- The variable you're using to flag which method to run should be marked volatile.
The most typical way to cancel, resume, or influence an operation taking place on another thread in C# is to use a shared variable to communicate. For example, the first thread could set a flag to true if you want to switch algorithms, and the background thread could check the flag after each run and switch if necessary.
One fleshed-out implementation of this in .NET is CancellationToken
.
精彩评论