我正在使用类似以下的函数。我正在使用异步系列来测试异步功能。该系列中的第一个回调工作正常,并且在名为callThisGuy(client,callback)的第二个方法处都中断了
testFunction: () ->
client = @
ASync.series([
(callback) ->
client.createSingleClient(callback)
(callback) ->
client.callThisMethod(client, callback)
(callback) ->
trace "In the next step"
],
(err, results) ->
trace "Test"
)
Run Code Online (Sandbox Code Playgroud)
这是callThisMethod函数
callThisMethod:(client, callback) ->
if(client.status == "new")
callback(null," ")
else
setTimeout ( ->
client.callThisMethod(client, callback)
), 1000
Run Code Online (Sandbox Code Playgroud)
即使状态不是“新”,也永远不会调用setTimeout函数。相反,它跳到下一步。我在没有Mocha的情况下运行了相同的代码,然后超时工作正常。
在摩卡咖啡中,它不起作用。我还检查了setTimeout是否未定义。它已定义。我想知道我是否想念一些东西。
private async Task<PortalODataContext> CallConnection(Connection connection)
{
bool cancel = false;
connection.Connected = true;
var task = getConnection(connection);
while (!cancel && !task.IsCompleted)
{
Thread.Sleep(100);
if (connection.Disconected)
{
cancel = true;
}
}
return await task;
}
Run Code Online (Sandbox Code Playgroud)
这是我在主线程上调用的函数,如下所示:
PortalODataContext portalContext = await this.CallConnection(connectionOpen);
Run Code Online (Sandbox Code Playgroud)
我是async的新手,等待所以我只想弄清楚为什么我的任务"CallConnection"会阻止我的主UI线程...你能帮助我吗?
哦,还有GetConnection:
private Task<PortalODataContext> getConnection(Connection connection)
{
return Task.Factory.StartNew(() =>
{
try
{
var context = connection.ConnectToPortal();
connection.ListTemplateLib = this.ShellModel.ConnectionManager.GetTemplateLibrarys(connection);
connection.ListTemplateGrp = this.ShellModel.ConnectionManager.GetTemplateGroups(connection, connection.TemplateLibraryId);
connection.ListTemplates = this.ShellModel.ConnectionManager.GetTemplates(connection, connection.TemplateGroupId);
return context;
}
catch (Exception)
{
throw;
}
});
Run Code Online (Sandbox Code Playgroud)
提前致谢
我开始使用async/await了.我使用基于MVVM模式的WPF编写了简单的应用程序,但它没有像我预期的那样工作.该程序的工作原理是没有异步函数:执行执行函数后,只有在循环函数结束后才会冻结和解冻.
请告诉我哪个部分出错了.我很感激任何反馈.:)
这是我的modelview类.它继承自wpf类,它包含标准wpf函数的定义,如OnPropertyChanged.
public class ModelView : wpf
{
string _state;
public string state { get { return _state; } set { _state = value; OnPropertyChanged("state"); } }
public DelegateCommand work { get; set; }
public ModelView()
{
state = "Program started";
work=new DelegateCommand(_work);
}
async void _work(object parameter)
{
state = "Working...";
int j=await loop();
state = "Done: " + j;
}
async Task<int> loop()
{
int i;
for(i=0;i<1000000000;i++);
return i;
}
}
Run Code Online (Sandbox Code Playgroud) 我有个问题:
我在F#中使用Async.Sleep()方法时遇到问题.这是我程序中的一段代码:
if (newAngle <> currentAngle) then
if (newAngle = 0) then
Motor(MotorPort.OutA).SetSpeed(100y)
angle1 <- Motor(MotorPort.OutA).GetTachoCount()
**Async.Sleep(20)**
angle2 <- Motor(MotorPort.OutA).GetTachoCount()
speed <- abs(angle2 - angle1)
distance <- abs(newAngle - angle2)
if (speed > 11) then
pwr <- 20L + int64 distance
if (pwr < 100L) then
Motor(MotorPort.OutA).SetSpeed(sbyte pwr)
while (distance > 30 || angle2 <> angle1) do
angle1 <- Motor(MotorPort.OutA).GetTachoCount()
**Async.Sleep(20)**
angle2 <- Motor(MotorPort.OutA).GetTachoCount()
speed <- abs(angle2 - angle1)
distance <- abs(newAngle - angle2)
if (speed > 11) then
pwr …Run Code Online (Sandbox Code Playgroud) 我正在处理的应用程序应该使用http客户端检索json字符串,然后在应用程序中进行反序列化并使用它.
一切正常,除了等待功能.我做错了什么,我似乎无法弄清楚是什么.我如何确保我的DataService类等待,直到我有我的json并且它已被反序列化?
DataService类:
class DataService : IDataService
{
private IEnumerable<Concert> _concerts;
public DataService()
{
_concerts = new DataFromAPI()._concerts;
Debug.WriteLine("____Deserialization should be done before continuing____");
**other tasks that need the json**
}
}
Run Code Online (Sandbox Code Playgroud)
我的http客户端类:
class DataFromAPI
{
public IEnumerable<Concert> _concerts { get; set; }
public DataFromAPI()
{
Retrieve();
}
public async Task Retrieve()
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
var result = await client.GetAsync(new Uri("http://url-of-my-api"), HttpCompletionOption.ResponseContentRead);
string jsonstring = await result.Content.ReadAsStringAsync();
DownloadCompleted(jsonstring);
}
catch …Run Code Online (Sandbox Code Playgroud) 我有这个代码:
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
using (WebResponse myResponse = myRequest.GetResponse())
{
using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
Run Code Online (Sandbox Code Playgroud)
我想在完成此请求后运行此代码:
MessageBox.Show("Finish");
Run Code Online (Sandbox Code Playgroud)
此外,当我运行此代码时,我的程序变得冻结.我认为这个问题可以通过异步HttpWebRequest来解决.
请看这段代码:
class Program
{
static async void DoStuff()
{
StreamWriter s = new StreamWriter("a.txt");
WebClient wc = new WebClient();
await wc.DownloadStringTaskAsync(new Uri("http://www.microsoft.com")); //1
//await s.WriteAsync ("123"); //2
Thread.Sleep(10000);
Console.WriteLine("DoStuffEnd");
}
static void Main(string[] args)
{
Program.DoStuff();
Console.WriteLine("MainEnd");
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud)
根据async/await的逻辑,在这种情况下一切正常.
输出:
MainEnd
10秒后
DoStuffEnd
但如果我评论(1)和取消注释(2),输出是:
10秒后
DoStuffEnd
MainEnd
为什么?
我能够通过输入表单Stephen Cleary解决问题.请参阅更新3.
我有一个Windows窗体应用程序,其中包含一个带有async修饰符的方法.如果在按钮的click事件中调用该方法,则它不会阻止UI线程.但是,当我在计时器内调用它作为回调时,它会冻结UI.我无法弄清楚我在这里做错了什么.请看下面我的代码.这只是一个用于演示目的的示例项目.
public Form1()
{
InitializeComponent();
}
private async void formCloseAsync()
{
shutdown stf = new shutdown();
stf.StartPosition = FormStartPosition.CenterScreen;
stf.Show();
var task = Task.Factory.StartNew(processClose);
await task;
}
private void processClose()
{
Thread.Sleep(5000);
Environment.Exit(1);
}
private void simpleButtonAsync_Click(object sender, EventArgs e)
{
formCloseAsync();
}
private void _simpleButtonTimer_Click(object sender, EventArgs e)
{
Timer _shutdownTimer = new Timer(delegate
{
formCloseAsync();
}, null, 5000, Timeout.Infinite);
}
Run Code Online (Sandbox Code Playgroud)
更新1:谢谢大家的宝贵意见.请参阅下面的更新代码
public Form1()
{
InitializeComponent();
}
private Timer _shutdownTimer;
private void formCloseAsync()
{
shutdown stf = …Run Code Online (Sandbox Code Playgroud) 我们知道$.ajax()这是一个异步方法,beacuse next语句在ajax()方法完全执行之前开始执行,'ajax()'继续并行执行他的东西,并且hide()是一个Synchronous方法,因为它会立即隐藏元素,而下一个语句将在hide()真正完成时执行他的整个任务,但我真的很困惑hide("slow").它看起来像异步,但我读过,它在浏览器中设置了计时器,一切都自动发生(现在hide("slow")没有任何并行),所以在某种程度上,它也在下一个语句开始执行之前完成了它的整个任务,所以 hide("slow")似乎也是同步方法,
我对这种同步异步概念非常困惑
有人能帮我理解这个概念吗?
我们如何在没有 out 参数的 C# 中安全地使用 async-await。
例如
async public void someMethod(){
await someOtherMethod (out string outputFromSomeOtherMethod);
.......
.....
}
Run Code Online (Sandbox Code Playgroud) asynchronous ×10
c# ×7
async-await ×5
coffeescript ×1
f# ×1
javascript ×1
jquery ×1
json ×1
mocha.js ×1
mvvm ×1
node.js ×1
synchronous ×1
task ×1
timer ×1
winforms ×1
wpf ×1