I have a function(f1) and at some point it calls another function(f2). I don't expect a response from f2, just calling it would be enough. But this f2 may take some time to execute. What I want is f1 to async-call f2 and carry on with the rest of it's(f1's) work. How can this be done in Springboot?
private void f1(){ //first function
//some logic
f2(); //calling second function
//some more logic
}
Related
I'm looking to find a way to have HaxeFlixel wait one second before an action, but FlxTimer isn't being useful. Thanks.
Create a timer variable and assign a callback function. This code will wait for one second before running the sayHello() function:
var timer:FlxTimer = new FlxTimer().start(1, sayHello);
...
private function sayHello(timer:FlxTimer)
{
trace("Hello!!");
}
I have a use case which fits well with the durable functions sequence example: push a json payload through three functions, each of which modifies the json graph and forwards it to the next function.
In the sequence example the result of the sequence is retrieved by issuing a query to the orchestrator.
In my use case I want to directly return the result of the three functions, essentially as the response of the third function.
Is there a way to do this? Is it even wise?
This is certainly doable. You can start with an HTTP trigger to start the orchestration and use the GetStatusAsync API inside your function to poll and wait for it to complete. Once completed, you can return the result from your HTTP trigger.
Something like this, perhaps:
public static async Task<JObject> Run(JObject input, DurableOrchestrationClient client)
{
string instanceId = await client.StartAsync("MyOrchestration", input);
for (int i = 0; i < 60; i++)
{
var status = await client.GetStatusAsync(instanceId);
if (status?.RuntimeStatus == "Completed")
{
return (JObject)status.Output;
}
// handle other status conditions, like failure
await Task.Delay(TimeSpan.FromSeconds(1));
}
// handle timeouts
}
As you can see from the code, the issue you'll have is dealing with error conditions. For example, what does your function do if the orchestration fails? Also, what if it takes a long time to finish? Those are things you can certainly figure out, but you'll want to code defensively to handle these cases.
I am building an audio player that plays '.wav' files and I have a problem with the callback function called from waveOutOpen() API.
Opening the output audio device for playback:
MMRESULT mRes = waveOutOpen(m_hWO,WAVE_MAPPER,&wFmt,(DWORD)&waveOutProc,(DWORD)this, CALLBACK_FUNCTION);
Implementation of callback function:
void CPlayWave::waveOutProc(HWAVEOUT m_hWO,UINT uMsg,DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
MMRESULT mmRes;
CPlayWave *pPW = (CPlayWave*)dwInstance;
switch(uMsg)
{
case MM_WOM_DONE: //playback finished
mmRes = waveOutUnprepareHeader(m_hWO, &pPW->m_WHdr, sizeof(WAVEHDR));
if(mmRes!=MMSYSERR_NOERROR)
{
//error handling
.....
}
mmRes = waveOutClose(m_hWO);
if(mmRes!=MMSYSERR_NOERROR)
{
//error handling
.....
}
AfxMessageBox("Finished playing the file");
m_bPlay = FALSE; //boolean flag used for pausing
break;
case WIM_DATA:
//for recording completion
break;
}
}
The problem is the MM_WOM_DONE never occurs and the callback function is never called after the playback of the file is completed. If a thread has to be used instead of callback function, can someone give me a simple example on how to use a callback thread(haven't found on net).
Also waveOutReset() documentation suggests that it closes all the buffers and returns to the system, so for handling the Stop-button in my application, I used the waveOutReset() function but, this causing the application to freeze. Why is this happening? Is there any alternative method to stop playing while buffer is still in queue for playback.
Callback function probably can not be a method of your class CPlayWave itself. It must be simple function out of your class with requested prototype.
void CALLBACK waveOutProc(HWAVEOUT m_hWO, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2) {
...
}
It must be, of course, declared/defined before you call waveOutOpen(). In addition, function name is pointer itself and ampersand & is not needed. Thus calling waveOutOpen() should be:
MMRESULT mRes = waveOutOpen(m_hWO, WAVE_MAPPER, &wFmt, (DWORD_PTR) waveOutProc, (DWORD_PTR) this, CALLBACK_FUNCTION | WAVE_ALLOWSYNC);
Also you there are only few system functions you can call from waveOutProc:
"Applications should not call any system-defined functions from inside a callback function, except for EnterCriticalSection, LeaveCriticalSection, midiOutLongMsg, midiOutShortMsg, OutputDebugString, PostMessage, PostThreadMessage, SetEvent, timeGetSystemTime, timeGetTime, timeKillEvent, and timeSetEvent. Calling other wave functions will cause deadlock."
So calling funcitons like AfxMessageBox or waveOutUnprepareHeader might be cause terrible issues.
I have a backgroundworker_dowork() event in C# .Net 4, that calls three methods, and I want them to execute synchronously.
Given my constraints, method 3 must execute after method 2, and method 2 must execute after method 1.
However, in the BackgroundWorker all three methods are executed asynchronously.
How can I change this?
private void bgwLoading_DoWork(object sender, DoWorkEventArgs e)
{
ArrayList a = (ArrayList)e.Argument;
string[] fileNames = (string[])a[0];
bool isLoad = (bool)a[1];
this.loadMultiImages(fileNames, isLoad);
}
private void loadMultiImages(string[] fileNames, bool isLoad)
{
// I want to execute the following codes sequentially.
Bitmap newBtmap = saveJpeg();
this.SafeInvoke(d => d.imageList.Images.Add(newBtmap));
}
Since SafeInvoke() takes less time than saveJpeg(), it starts executing before the saveJpeg() is done, changing the flow of the execution I want.
If method 3 depends on method 2 and method 2 depends on method 1, then there is only one way to execute them: sequentially. Even if you task multiple threads with executing them, you'll still have to execute the methods in order 1->2->3.
You can use various constructs to force method 2 to wait for method 1 and method 3 to wait for method 2, but you're still fundamentally executing the methods synchronously so you might as well just use 1 thread to execute all 3 methods.
You may want something like this. Use the RunWorkerCompleted event to call a method after the background operation completes:
var bg1 = new System.ComponentModel.BackgroundWorker();
var bg2 = new System.ComponentModel.BackgroundWorker();
var bg3 = new System.ComponentModel.BackgroundWorker();
bg1.RunWorkerCompleted += (s, e) =>
{
bg2.RunWorkerAsync();
};
bg2.RunWorkerCompleted += (s, e) =>
{
bg3.RunWorkerAsync();
};
bg1.RunWorkerAsync();
But, I'm not sure on the effectiveness of this pattern. If you want functions called synchronously, then call them synchronously. There's probably a better way to do that than using background workers.
If you want to run 3 procedures synchronously in the background, just call them synchronously in the background thread:
var bg1 = new System.ComponentModel.BackgroundWorker();
bg1.DoWork += (s, e) =>
{
Process1();
Process2();
Process3();
};
bg1.RunWorkerAsync();
We are developing a WPF application using TDD. As we're already working on this solution for almost two years, we've written a huge bunch of tests (almost 2000 Unittests right now).
There are some classes, that need to implement functionality multithreaded and asynchronously. For example a communication-component that can both send and receive messages and parse them. The dependencies are always mocked using RhinoMocks.
Our Test-Methods targeting these classes look very similar, as following:
[TestMethod]
public void Method_Description_ExpectedResult(){
// Arrange
var myStub = MockRepository.GenerateStub<IMyStub>();
var target = new MyAsynchronousClass(myStub);
// Act
var target.Send("Foo");
Thread.Sleep(200);
//Assert
myStub.AssertWasCalled(x => x.Bar("Foo"));
}
As you can see, this test runs at least for 200 ms due to the Thread.Sleep(). We optimized the test replacing the AssertWasCalled with a active polling method, s.th. like this:
public static bool True(Func<bool> condition, int times, int waitTime)
{
for (var i = 0; i < times; i++)
{
if (condition())
return true;
Thread.Sleep(waitTime);
}
return condition();
}
We can now use this WaitFor.True(...) Method by changing the AssertWasCalled to:
var fooTriggered = false;
myStub.Stub(x => x.Bar("Foo")).Do((Action)(() => fooTriggered = true)));
WaitFor.True(() => fooTriggered, 20, 20);
Assert.IsTrue(fooTriggered);
This construct will terminate earlier if the condition matches, but anyway - this takes too long for us. Running all of our 2000 Tests need about 5 Minutes (building and running them).
Is there any smart trick how we could optimize code like this?
You can use a monitor. I'm making this up so please excuse me if it isn't quite compiling, but it'll look something like:
[TestMethod]
public void Method_Description_ExpectedResult(){
// Arrange
var waitingRoom = new object();
var myStub = MockRepository.GenerateStub<IMyStub>();
myStub.Setup(x => x.Bar("Foo")).Callback(x =>
{
Monitor.Enter(waitingRoom);
Monitor.Pulse(waitingRoom);
Monitor.Exit(waitingRoom);
}
var target = new MyAsynchronousClass(myStub);
// Act
Monitor.Enter(waitingRoom);
target.Send("Foo");
Monitor.Wait(waitingRoom);
Monitor.Exit(waitingRoom);
//Assert
myStub.AssertWasCalled(x => x.Bar("Foo"));
}
Code written within the Monitor can't run until it's free. The test will cause the acting thread to wait until Monitor.Wait has been called. Then the callback can enter and pulse the Monitor. The test then "wakes up", and once the callback has exited the monitor, it gets control back and exits too, allowing you to Assert.
The only thing I haven't covered is that if Bar("Foo") doesn't get called it will hang, so you might want to have a timer pulse the thread too.
You can create a class which does the complex monitoring bits for you if you use it a lot. This is one I wrote to deal with asynchronous checks in UI automation; adapting it for what you're doing might help you.