How to call asynchronous method from synchronous method in C#?

后端 未结 15 1044
星月不相逢
星月不相逢 2020-11-21 06:27

I have a public async void Foo() method that I want to call from synchronous method. So far all I have seen from MSDN documentation is calling async methods via

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:46

    Here is the simplest solution. I saw it somewhere on the Internet, I didn't remember where, but I have been using it successfully. It will not deadlock the calling thread.

        void Synchronous Function()
        {
            Task.Run(Foo).Wait();
        }
    
        string SynchronousFunctionReturnsString()
        {
            return Task.Run(Foo).Result;
        }
    
        string SynchronousFunctionReturnsStringWithParam(int id)
        {
            return Task.Run(() => Foo(id)).Result;
        }
    

提交回复
热议问题