سؤال

I have a method that I use to get string from web service

I started the code with

    var task = _tempClient.GetteststringAsync();
    string teststring = await task;

but I noticed that the code not wait till the call end and the value retrieved ,so I tried something like

    string teststring= string.Empty;
    var t1 = Task.Factory.StartNew(new Func<Task>(async () => teststring= await _tempClient.GetteststringAsync()))
.Unwrap();
    t1.Wait();

but this cause the application stuck , any idea how to make it work ,tempClient is a service refrence object . I use it to intialise the webrefrence in MVC Application, it's the helper class

هل كانت مفيدة؟

المحلول 2

I solved it using

http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx using this code looks like

AsyncPump.Run(async delegate

{

    await DemoAsync();

});

نصائح أخرى

Your first attempt was much closer to doing the right thing, calling task.Wait() or task.Result is a blocking call and can often cause a deadlock. Have a look at this article for async/await best practices.

What you want to do is what you had first:

var task = _tempClient.GetteststringAsync();
string teststring = await task;

Calling _tempClient.GetteststringAsync() will start executing on a thread pool thread and once finished the result will be returned into teststring and the rest of the method will execute on the original request thread. At that point you just need to do whatever you need to with teststring.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top